Fix Trac #2246; overhaul handling of overloaded literals
[ghc-hetmet.git] / compiler / deSugar / DsMeta.hs
1 -----------------------------------------------------------------------------
2 --
3 -- (c) The University of Glasgow 2006
4 --
5 -- The purpose of this module is to transform an HsExpr into a CoreExpr which
6 -- when evaluated, returns a (Meta.Q Meta.Exp) computation analogous to the
7 -- input HsExpr. We do this in the DsM monad, which supplies access to
8 -- CoreExpr's of the "smart constructors" of the Meta.Exp datatype.
9 --
10 -- It also defines a bunch of knownKeyNames, in the same way as is done
11 -- in prelude/PrelNames.  It's much more convenient to do it here, becuase
12 -- otherwise we have to recompile PrelNames whenever we add a Name, which is
13 -- a Royal Pain (triggers other recompilation).
14 -----------------------------------------------------------------------------
15
16 {-# OPTIONS -fno-warn-unused-imports #-}
17 -- The above warning supression flag is a temporary kludge.
18 -- While working on this module you are encouraged to remove it and fix
19 -- any warnings in the module. See
20 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
21 -- for details
22
23 module DsMeta( dsBracket, 
24                templateHaskellNames, qTyConName, nameTyConName,
25                liftName, expQTyConName, patQTyConName, decQTyConName, typeQTyConName,
26                decTyConName, typeTyConName, mkNameG_dName, mkNameG_vName, mkNameG_tcName,
27                quoteExpName, quotePatName
28                 ) where
29
30 import {-# SOURCE #-}   DsExpr ( dsExpr )
31
32 import MatchLit
33 import DsUtils
34 import DsMonad
35
36 import qualified Language.Haskell.TH as TH
37
38 import HsSyn
39 import Class
40 import PrelNames
41 -- To avoid clashes with DsMeta.varName we must make a local alias for
42 -- OccName.varName we do this by removing varName from the import of
43 -- OccName above, making a qualified instance of OccName and using
44 -- OccNameAlias.varName where varName ws previously used in this file.
45 import qualified OccName
46
47 import Module
48 import Id
49 import Name
50 import NameEnv
51 import TcType
52 import TyCon
53 import TysWiredIn
54 import CoreSyn
55 import CoreUtils
56 import SrcLoc
57 import Unique
58 import BasicTypes
59 import Outputable
60 import Bag
61 import FastString
62 import ForeignCall
63
64 import Data.Maybe
65 import Control.Monad
66 import Data.List
67
68 -----------------------------------------------------------------------------
69 dsBracket :: HsBracket Name -> [PendingSplice] -> DsM CoreExpr
70 -- Returns a CoreExpr of type TH.ExpQ
71 -- The quoted thing is parameterised over Name, even though it has
72 -- been type checked.  We don't want all those type decorations!
73
74 dsBracket brack splices
75   = dsExtendMetaEnv new_bit (do_brack brack)
76   where
77     new_bit = mkNameEnv [(n, Splice (unLoc e)) | (n,e) <- splices]
78
79     do_brack (VarBr n)  = do { MkC e1  <- lookupOcc n ; return e1 }
80     do_brack (ExpBr e)  = do { MkC e1  <- repLE e     ; return e1 }
81     do_brack (PatBr p)  = do { MkC p1  <- repLP p     ; return p1 }
82     do_brack (TypBr t)  = do { MkC t1  <- repLTy t    ; return t1 }
83     do_brack (DecBr ds) = do { MkC ds1 <- repTopDs ds ; return ds1 }
84
85 {- -------------- Examples --------------------
86
87   [| \x -> x |]
88 ====>
89   gensym (unpackString "x"#) `bindQ` \ x1::String ->
90   lam (pvar x1) (var x1)
91
92
93   [| \x -> $(f [| x |]) |]
94 ====>
95   gensym (unpackString "x"#) `bindQ` \ x1::String ->
96   lam (pvar x1) (f (var x1))
97 -}
98
99
100 -------------------------------------------------------
101 --                      Declarations
102 -------------------------------------------------------
103
104 repTopDs :: HsGroup Name -> DsM (Core (TH.Q [TH.Dec]))
105 repTopDs group
106  = do { let { bndrs = map unLoc (groupBinders group) } ;
107         ss <- mkGenSyms bndrs ;
108
109         -- Bind all the names mainly to avoid repeated use of explicit strings.
110         -- Thus we get
111         --      do { t :: String <- genSym "T" ;
112         --           return (Data t [] ...more t's... }
113         -- The other important reason is that the output must mention
114         -- only "T", not "Foo:T" where Foo is the current module
115
116         
117         decls <- addBinds ss (do {
118                         val_ds  <- rep_val_binds (hs_valds group) ;
119                         tycl_ds <- mapM repTyClD (hs_tyclds group) ;
120                         inst_ds <- mapM repInstD' (hs_instds group) ;
121                         for_ds <- mapM repForD (hs_fords group) ;
122                         -- more needed
123                         return (de_loc $ sort_by_loc $ val_ds ++ catMaybes tycl_ds ++ inst_ds ++ for_ds) }) ;
124
125         decl_ty <- lookupType decQTyConName ;
126         let { core_list = coreList' decl_ty decls } ;
127
128         dec_ty <- lookupType decTyConName ;
129         q_decs  <- repSequenceQ dec_ty core_list ;
130
131         wrapNongenSyms ss q_decs
132         -- Do *not* gensym top-level binders
133       }
134
135 groupBinders :: HsGroup Name -> [Located Name]
136 groupBinders (HsGroup { hs_valds = val_decls, hs_tyclds = tycl_decls,
137                         hs_fords = foreign_decls })
138 -- Collect the binders of a Group
139   = collectHsValBinders val_decls ++
140     [n | d <- tycl_decls, n <- tyClDeclNames (unLoc d)] ++
141     [n | L _ (ForeignImport n _ _) <- foreign_decls]
142
143
144 {-      Note [Binders and occurrences]
145         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
146 When we desugar [d| data T = MkT |]
147 we want to get
148         Data "T" [] [Con "MkT" []] []
149 and *not*
150         Data "Foo:T" [] [Con "Foo:MkT" []] []
151 That is, the new data decl should fit into whatever new module it is
152 asked to fit in.   We do *not* clone, though; no need for this:
153         Data "T79" ....
154
155 But if we see this:
156         data T = MkT 
157         foo = reifyDecl T
158
159 then we must desugar to
160         foo = Data "Foo:T" [] [Con "Foo:MkT" []] []
161
162 So in repTopDs we bring the binders into scope with mkGenSyms and addBinds.
163 And we use lookupOcc, rather than lookupBinder
164 in repTyClD and repC.
165
166 -}
167
168 repTyClD :: LTyClDecl Name -> DsM (Maybe (SrcSpan, Core TH.DecQ))
169
170 repTyClD (L loc (TyData { tcdND = DataType, tcdCtxt = cxt, 
171                     tcdLName = tc, tcdTyVars = tvs, 
172                     tcdCons = cons, tcdDerivs = mb_derivs }))
173  = do { tc1 <- lookupLOcc tc ;          -- See note [Binders and occurrences] 
174         dec <- addTyVarBinds tvs $ \bndrs -> do {
175                cxt1    <- repLContext cxt ;
176                cons1   <- mapM repC cons ;
177                cons2   <- coreList conQTyConName cons1 ;
178                derivs1 <- repDerivs mb_derivs ;
179                bndrs1  <- coreList nameTyConName bndrs ;
180                repData cxt1 tc1 bndrs1 cons2 derivs1 } ;
181         return $ Just (loc, dec) }
182
183 repTyClD (L loc (TyData { tcdND = NewType, tcdCtxt = cxt, 
184                     tcdLName = tc, tcdTyVars = tvs, 
185                     tcdCons = [con], tcdDerivs = mb_derivs }))
186  = do { tc1 <- lookupLOcc tc ;          -- See note [Binders and occurrences] 
187         dec <- addTyVarBinds tvs $ \bndrs -> do {
188                cxt1   <- repLContext cxt ;
189                con1   <- repC con ;
190                derivs1 <- repDerivs mb_derivs ;
191                bndrs1  <- coreList nameTyConName bndrs ;
192                repNewtype cxt1 tc1 bndrs1 con1 derivs1 } ;
193         return $ Just (loc, dec) }
194
195 repTyClD (L loc (TySynonym { tcdLName = tc, tcdTyVars = tvs, tcdSynRhs = ty }))
196  = do { tc1 <- lookupLOcc tc ;          -- See note [Binders and occurrences] 
197         dec <- addTyVarBinds tvs $ \bndrs -> do {
198                ty1     <- repLTy ty ;
199                bndrs1  <- coreList nameTyConName bndrs ;
200                repTySyn tc1 bndrs1 ty1 } ;
201         return (Just (loc, dec)) }
202
203 repTyClD (L loc (ClassDecl { tcdCtxt = cxt, tcdLName = cls, 
204                       tcdTyVars = tvs, 
205                       tcdFDs = fds,
206                       tcdSigs = sigs, tcdMeths = meth_binds }))
207  = do { cls1 <- lookupLOcc cls ;                -- See note [Binders and occurrences] 
208         dec  <- addTyVarBinds tvs $ \bndrs -> do {
209                   cxt1   <- repLContext cxt ;
210                   sigs1  <- rep_sigs sigs ;
211                   binds1 <- rep_binds meth_binds ;
212                   fds1 <- repLFunDeps fds;
213                   decls1 <- coreList decQTyConName (sigs1 ++ binds1) ;
214                   bndrs1 <- coreList nameTyConName bndrs ;
215                   repClass cxt1 cls1 bndrs1 fds1 decls1 } ;
216         return $ Just (loc, dec) }
217
218 -- Un-handled cases
219 repTyClD (L loc d) = putSrcSpanDs loc $
220                      do { warnDs (hang ds_msg 4 (ppr d))
221                         ; return Nothing }
222
223 -- represent fundeps
224 --
225 repLFunDeps :: [Located (FunDep Name)] -> DsM (Core [TH.FunDep])
226 repLFunDeps fds = do fds' <- mapM repLFunDep fds
227                      fdList <- coreList funDepTyConName fds'
228                      return fdList
229
230 repLFunDep :: Located (FunDep Name) -> DsM (Core TH.FunDep)
231 repLFunDep (L _ (xs, ys)) = do xs' <- mapM lookupBinder xs
232                                ys' <- mapM lookupBinder ys
233                                xs_list <- coreList nameTyConName xs'
234                                ys_list <- coreList nameTyConName ys'
235                                repFunDep xs_list ys_list
236
237 repInstD' :: LInstDecl Name -> DsM (SrcSpan, Core TH.DecQ)
238 repInstD' (L loc (InstDecl ty binds _ _))               -- Ignore user pragmas for now
239  = do   { i <- addTyVarBinds tvs $ \_ ->
240                 -- We must bring the type variables into scope, so their occurrences
241                 -- don't fail,  even though the binders don't appear in the resulting 
242                 -- data structure
243                 do {  cxt1 <- repContext cxt
244                    ; inst_ty1 <- repPred (HsClassP cls tys)
245                    ; ss <- mkGenSyms (collectHsBindBinders binds)
246                    ; binds1 <- addBinds ss (rep_binds binds)
247                    ; decls1 <- coreList decQTyConName binds1
248                    ; decls2 <- wrapNongenSyms ss decls1
249                    -- wrapNonGenSyms: do not clone the class op names!
250                    -- They must be called 'op' etc, not 'op34'
251                    ; repInst cxt1 inst_ty1 decls2 }
252
253         ; return (loc, i)}
254  where
255    (tvs, cxt, cls, tys) = splitHsInstDeclTy (unLoc ty)
256
257 repForD :: Located (ForeignDecl Name) -> DsM (SrcSpan, Core TH.DecQ)
258 repForD (L loc (ForeignImport name typ (CImport cc s ch cn cis)))
259  = do MkC name' <- lookupLOcc name
260       MkC typ' <- repLTy typ
261       MkC cc' <- repCCallConv cc
262       MkC s' <- repSafety s
263       cis' <- conv_cimportspec cis
264       MkC str <- coreStringLit $ static
265                               ++ unpackFS ch ++ " "
266                               ++ unpackFS cn ++ " "
267                               ++ cis'
268       dec <- rep2 forImpDName [cc', s', str, name', typ']
269       return (loc, dec)
270  where
271     conv_cimportspec (CLabel cls) = notHandled "Foreign label" (doubleQuotes (ppr cls))
272     conv_cimportspec (CFunction DynamicTarget) = return "dynamic"
273     conv_cimportspec (CFunction (StaticTarget fs)) = return (unpackFS fs)
274     conv_cimportspec CWrapper = return "wrapper"
275     static = case cis of
276                  CFunction (StaticTarget _) -> "static "
277                  _ -> ""
278 repForD decl = notHandled "Foreign declaration" (ppr decl)
279
280 repCCallConv :: CCallConv -> DsM (Core TH.Callconv)
281 repCCallConv CCallConv = rep2 cCallName []
282 repCCallConv StdCallConv = rep2 stdCallName []
283 repCCallConv CmmCallConv = notHandled "repCCallConv" (ppr CmmCallConv)
284
285 repSafety :: Safety -> DsM (Core TH.Safety)
286 repSafety PlayRisky = rep2 unsafeName []
287 repSafety (PlaySafe False) = rep2 safeName []
288 repSafety (PlaySafe True) = rep2 threadsafeName []
289
290 ds_msg :: SDoc
291 ds_msg = ptext (sLit "Cannot desugar this Template Haskell declaration:")
292
293 -------------------------------------------------------
294 --                      Constructors
295 -------------------------------------------------------
296
297 repC :: LConDecl Name -> DsM (Core TH.ConQ)
298 repC (L _ (ConDecl con _ [] (L _ []) details ResTyH98 _))
299   = do { con1 <- lookupLOcc con ;               -- See note [Binders and occurrences] 
300          repConstr con1 details }
301 repC (L loc (ConDecl con expl tvs (L cloc ctxt) details ResTyH98 doc))
302   = do { addTyVarBinds tvs $ \bndrs -> do {
303              c' <- repC (L loc (ConDecl con expl [] (L cloc []) details ResTyH98 doc));
304              ctxt' <- repContext ctxt;
305              bndrs' <- coreList nameTyConName bndrs;
306              rep2 forallCName [unC bndrs', unC ctxt', unC c']
307          }
308        }
309 repC (L loc con_decl)           -- GADTs
310   = putSrcSpanDs loc $
311     notHandled "GADT declaration" (ppr con_decl) 
312
313 repBangTy :: LBangType Name -> DsM (Core (TH.StrictTypeQ))
314 repBangTy ty= do 
315   MkC s <- rep2 str []
316   MkC t <- repLTy ty'
317   rep2 strictTypeName [s, t]
318   where 
319     (str, ty') = case ty of
320                    L _ (HsBangTy _ ty) -> (isStrictName,  ty)
321                    _                   -> (notStrictName, ty)
322
323 -------------------------------------------------------
324 --                      Deriving clause
325 -------------------------------------------------------
326
327 repDerivs :: Maybe [LHsType Name] -> DsM (Core [TH.Name])
328 repDerivs Nothing = coreList nameTyConName []
329 repDerivs (Just ctxt)
330   = do { strs <- mapM rep_deriv ctxt ; 
331          coreList nameTyConName strs }
332   where
333     rep_deriv :: LHsType Name -> DsM (Core TH.Name)
334         -- Deriving clauses must have the simple H98 form
335     rep_deriv (L _ (HsPredTy (HsClassP cls []))) = lookupOcc cls
336     rep_deriv other = notHandled "Non-H98 deriving clause" (ppr other)
337
338
339 -------------------------------------------------------
340 --   Signatures in a class decl, or a group of bindings
341 -------------------------------------------------------
342
343 rep_sigs :: [LSig Name] -> DsM [Core TH.DecQ]
344 rep_sigs sigs = do locs_cores <- rep_sigs' sigs
345                    return $ de_loc $ sort_by_loc locs_cores
346
347 rep_sigs' :: [LSig Name] -> DsM [(SrcSpan, Core TH.DecQ)]
348         -- We silently ignore ones we don't recognise
349 rep_sigs' sigs = do { sigs1 <- mapM rep_sig sigs ;
350                      return (concat sigs1) }
351
352 rep_sig :: LSig Name -> DsM [(SrcSpan, Core TH.DecQ)]
353         -- Singleton => Ok
354         -- Empty     => Too hard, signature ignored
355 rep_sig (L loc (TypeSig nm ty)) = rep_proto nm ty loc
356 rep_sig _                       = return []
357
358 rep_proto :: Located Name -> LHsType Name -> SrcSpan -> DsM [(SrcSpan, Core TH.DecQ)]
359 rep_proto nm ty loc = do { nm1 <- lookupLOcc nm ; 
360                        ty1 <- repLTy ty ; 
361                        sig <- repProto nm1 ty1 ;
362                        return [(loc, sig)] }
363
364
365 -------------------------------------------------------
366 --                      Types
367 -------------------------------------------------------
368
369 -- gensym a list of type variables and enter them into the meta environment;
370 -- the computations passed as the second argument is executed in that extended
371 -- meta environment and gets the *new* names on Core-level as an argument
372 --
373 addTyVarBinds :: [LHsTyVarBndr Name]             -- the binders to be added
374               -> ([Core TH.Name] -> DsM (Core (TH.Q a))) -- action in the ext env
375               -> DsM (Core (TH.Q a))
376 addTyVarBinds tvs m =
377   do
378     let names = map (hsTyVarName.unLoc) tvs
379     freshNames <- mkGenSyms names
380     term       <- addBinds freshNames $ do
381                     bndrs <- mapM lookupBinder names 
382                     m bndrs
383     wrapGenSyns freshNames term
384
385 -- represent a type context
386 --
387 repLContext :: LHsContext Name -> DsM (Core TH.CxtQ)
388 repLContext (L _ ctxt) = repContext ctxt
389
390 repContext :: HsContext Name -> DsM (Core TH.CxtQ)
391 repContext ctxt = do 
392                     preds    <- mapM repLPred ctxt
393                     predList <- coreList typeQTyConName preds
394                     repCtxt predList
395
396 -- represent a type predicate
397 --
398 repLPred :: LHsPred Name -> DsM (Core TH.TypeQ)
399 repLPred (L _ p) = repPred p
400
401 repPred :: HsPred Name -> DsM (Core TH.TypeQ)
402 repPred (HsClassP cls tys) = do
403                                tcon <- repTy (HsTyVar cls)
404                                tys1 <- repLTys tys
405                                repTapps tcon tys1
406 repPred p@(HsEqualP _ _) = notHandled "Equational constraint" (ppr p)
407 repPred p@(HsIParam _ _) = notHandled "Implicit parameter constraint" (ppr p)
408
409 -- yield the representation of a list of types
410 --
411 repLTys :: [LHsType Name] -> DsM [Core TH.TypeQ]
412 repLTys tys = mapM repLTy tys
413
414 -- represent a type
415 --
416 repLTy :: LHsType Name -> DsM (Core TH.TypeQ)
417 repLTy (L _ ty) = repTy ty
418
419 repTy :: HsType Name -> DsM (Core TH.TypeQ)
420 repTy (HsForAllTy _ tvs ctxt ty)  = 
421   addTyVarBinds tvs $ \bndrs -> do
422     ctxt1  <- repLContext ctxt
423     ty1    <- repLTy ty
424     bndrs1 <- coreList nameTyConName bndrs
425     repTForall bndrs1 ctxt1 ty1
426
427 repTy (HsTyVar n)
428   | isTvOcc (nameOccName n)       = do 
429                                       tv1 <- lookupTvOcc n
430                                       repTvar tv1
431   | otherwise                     = do 
432                                       tc1 <- lookupOcc n
433                                       repNamedTyCon tc1
434 repTy (HsAppTy f a)               = do 
435                                       f1 <- repLTy f
436                                       a1 <- repLTy a
437                                       repTapp f1 a1
438 repTy (HsFunTy f a)               = do 
439                                       f1   <- repLTy f
440                                       a1   <- repLTy a
441                                       tcon <- repArrowTyCon
442                                       repTapps tcon [f1, a1]
443 repTy (HsListTy t)                = do
444                                       t1   <- repLTy t
445                                       tcon <- repListTyCon
446                                       repTapp tcon t1
447 repTy (HsPArrTy t)                = do
448                                       t1   <- repLTy t
449                                       tcon <- repTy (HsTyVar (tyConName parrTyCon))
450                                       repTapp tcon t1
451 repTy (HsTupleTy _ tys)   = do
452                                       tys1 <- repLTys tys 
453                                       tcon <- repTupleTyCon (length tys)
454                                       repTapps tcon tys1
455 repTy (HsOpTy ty1 n ty2)          = repLTy ((nlHsTyVar (unLoc n) `nlHsAppTy` ty1) 
456                                            `nlHsAppTy` ty2)
457 repTy (HsParTy t)                 = repLTy t
458 repTy (HsPredTy pred)             = repPred pred
459 repTy ty@(HsNumTy _)              = notHandled "Number types (for generics)" (ppr ty)
460 repTy ty                          = notHandled "Exotic form of type" (ppr ty)
461
462
463 -----------------------------------------------------------------------------
464 --              Expressions
465 -----------------------------------------------------------------------------
466
467 repLEs :: [LHsExpr Name] -> DsM (Core [TH.ExpQ])
468 repLEs es = do { es'  <- mapM repLE es ;
469                  coreList expQTyConName es' }
470
471 -- FIXME: some of these panics should be converted into proper error messages
472 --        unless we can make sure that constructs, which are plainly not
473 --        supported in TH already lead to error messages at an earlier stage
474 repLE :: LHsExpr Name -> DsM (Core TH.ExpQ)
475 repLE (L loc e) = putSrcSpanDs loc (repE e)
476
477 repE :: HsExpr Name -> DsM (Core TH.ExpQ)
478 repE (HsVar x)            =
479   do { mb_val <- dsLookupMetaEnv x 
480      ; case mb_val of
481         Nothing          -> do { str <- globalVar x
482                                ; repVarOrCon x str }
483         Just (Bound y)   -> repVarOrCon x (coreVar y)
484         Just (Splice e)  -> do { e' <- dsExpr e
485                                ; return (MkC e') } }
486 repE e@(HsIPVar _) = notHandled "Implicit parameters" (ppr e)
487
488         -- Remember, we're desugaring renamer output here, so
489         -- HsOverlit can definitely occur
490 repE (HsOverLit l) = do { a <- repOverloadedLiteral l; repLit a }
491 repE (HsLit l)     = do { a <- repLiteral l;           repLit a }
492 repE (HsLam (MatchGroup [m] _)) = repLambda m
493 repE (HsApp x y)   = do {a <- repLE x; b <- repLE y; repApp a b}
494
495 repE (OpApp e1 op _ e2) =
496   do { arg1 <- repLE e1; 
497        arg2 <- repLE e2; 
498        the_op <- repLE op ;
499        repInfixApp arg1 the_op arg2 } 
500 repE (NegApp x _)        = do
501                               a         <- repLE x
502                               negateVar <- lookupOcc negateName >>= repVar
503                               negateVar `repApp` a
504 repE (HsPar x)            = repLE x
505 repE (SectionL x y)       = do { a <- repLE x; b <- repLE y; repSectionL a b } 
506 repE (SectionR x y)       = do { a <- repLE x; b <- repLE y; repSectionR a b } 
507 repE (HsCase e (MatchGroup ms _)) = do { arg <- repLE e
508                                        ; ms2 <- mapM repMatchTup ms
509                                        ; repCaseE arg (nonEmptyCoreList ms2) }
510 repE (HsIf x y z)         = do
511                               a <- repLE x
512                               b <- repLE y
513                               c <- repLE z
514                               repCond a b c
515 repE (HsLet bs e)         = do { (ss,ds) <- repBinds bs
516                                ; e2 <- addBinds ss (repLE e)
517                                ; z <- repLetE ds e2
518                                ; wrapGenSyns ss z }
519 -- FIXME: I haven't got the types here right yet
520 repE (HsDo DoExpr sts body _) 
521  = do { (ss,zs) <- repLSts sts; 
522         body'   <- addBinds ss $ repLE body;
523         ret     <- repNoBindSt body';   
524         e       <- repDoE (nonEmptyCoreList (zs ++ [ret]));
525         wrapGenSyns ss e }
526 repE (HsDo ListComp sts body _)
527  = do { (ss,zs) <- repLSts sts; 
528         body'   <- addBinds ss $ repLE body;
529         ret     <- repNoBindSt body';   
530         e       <- repComp (nonEmptyCoreList (zs ++ [ret]));
531         wrapGenSyns ss e }
532 repE e@(HsDo _ _ _ _) = notHandled "mdo and [: :]" (ppr e)
533 repE (ExplicitList _ es) = do { xs <- repLEs es; repListExp xs }
534 repE e@(ExplicitPArr _ _) = notHandled "Parallel arrays" (ppr e)
535 repE e@(ExplicitTuple es boxed) 
536   | isBoxed boxed         = do { xs <- repLEs es; repTup xs }
537   | otherwise             = notHandled "Unboxed tuples" (ppr e)
538 repE (RecordCon c _ flds)
539  = do { x <- lookupLOcc c;
540         fs <- repFields flds;
541         repRecCon x fs }
542 repE (RecordUpd e flds _ _ _)
543  = do { x <- repLE e;
544         fs <- repFields flds;
545         repRecUpd x fs }
546
547 repE (ExprWithTySig e ty) = do { e1 <- repLE e; t1 <- repLTy ty; repSigExp e1 t1 }
548 repE (ArithSeq _ aseq) =
549   case aseq of
550     From e              -> do { ds1 <- repLE e; repFrom ds1 }
551     FromThen e1 e2      -> do 
552                              ds1 <- repLE e1
553                              ds2 <- repLE e2
554                              repFromThen ds1 ds2
555     FromTo   e1 e2      -> do 
556                              ds1 <- repLE e1
557                              ds2 <- repLE e2
558                              repFromTo ds1 ds2
559     FromThenTo e1 e2 e3 -> do 
560                              ds1 <- repLE e1
561                              ds2 <- repLE e2
562                              ds3 <- repLE e3
563                              repFromThenTo ds1 ds2 ds3
564 repE (HsSpliceE (HsSplice n _)) 
565   = do { mb_val <- dsLookupMetaEnv n
566        ; case mb_val of
567                  Just (Splice e) -> do { e' <- dsExpr e
568                                        ; return (MkC e') }
569                  _ -> pprPanic "HsSplice" (ppr n) }
570                         -- Should not happen; statically checked
571
572 repE e@(PArrSeq {})      = notHandled "Parallel arrays" (ppr e)
573 repE e@(HsCoreAnn {})    = notHandled "Core annotations" (ppr e)
574 repE e@(HsSCC {})        = notHandled "Cost centres" (ppr e)
575 repE e@(HsTickPragma {}) = notHandled "Tick Pragma" (ppr e)
576 repE e@(HsBracketOut {}) = notHandled "TH brackets" (ppr e)
577 repE e                   = notHandled "Expression form" (ppr e)
578
579 -----------------------------------------------------------------------------
580 -- Building representations of auxillary structures like Match, Clause, Stmt, 
581
582 repMatchTup ::  LMatch Name -> DsM (Core TH.MatchQ) 
583 repMatchTup (L _ (Match [p] _ (GRHSs guards wheres))) =
584   do { ss1 <- mkGenSyms (collectPatBinders p) 
585      ; addBinds ss1 $ do {
586      ; p1 <- repLP p
587      ; (ss2,ds) <- repBinds wheres
588      ; addBinds ss2 $ do {
589      ; gs    <- repGuards guards
590      ; match <- repMatch p1 gs ds
591      ; wrapGenSyns (ss1++ss2) match }}}
592 repMatchTup _ = panic "repMatchTup: case alt with more than one arg"
593
594 repClauseTup ::  LMatch Name -> DsM (Core TH.ClauseQ)
595 repClauseTup (L _ (Match ps _ (GRHSs guards wheres))) =
596   do { ss1 <- mkGenSyms (collectPatsBinders ps) 
597      ; addBinds ss1 $ do {
598        ps1 <- repLPs ps
599      ; (ss2,ds) <- repBinds wheres
600      ; addBinds ss2 $ do {
601        gs <- repGuards guards
602      ; clause <- repClause ps1 gs ds
603      ; wrapGenSyns (ss1++ss2) clause }}}
604
605 repGuards ::  [LGRHS Name] ->  DsM (Core TH.BodyQ)
606 repGuards [L _ (GRHS [] e)]
607   = do {a <- repLE e; repNormal a }
608 repGuards other 
609   = do { zs <- mapM process other;
610      let {(xs, ys) = unzip zs};
611          gd <- repGuarded (nonEmptyCoreList ys);
612      wrapGenSyns (concat xs) gd }
613   where 
614     process :: LGRHS Name -> DsM ([GenSymBind], (Core (TH.Q (TH.Guard, TH.Exp))))
615     process (L _ (GRHS [L _ (ExprStmt e1 _ _)] e2))
616            = do { x <- repLNormalGE e1 e2;
617                   return ([], x) }
618     process (L _ (GRHS ss rhs))
619            = do (gs, ss') <- repLSts ss
620                 rhs' <- addBinds gs $ repLE rhs
621                 g <- repPatGE (nonEmptyCoreList ss') rhs'
622                 return (gs, g)
623
624 repFields :: HsRecordBinds Name -> DsM (Core [TH.Q TH.FieldExp])
625 repFields (HsRecFields { rec_flds = flds })
626   = do  { fnames <- mapM lookupLOcc (map hsRecFieldId flds)
627         ; es <- mapM repLE (map hsRecFieldArg flds)
628         ; fs <- zipWithM repFieldExp fnames es
629         ; coreList fieldExpQTyConName fs }
630
631
632 -----------------------------------------------------------------------------
633 -- Representing Stmt's is tricky, especially if bound variables
634 -- shadow each other. Consider:  [| do { x <- f 1; x <- f x; g x } |]
635 -- First gensym new names for every variable in any of the patterns.
636 -- both static (x'1 and x'2), and dynamic ((gensym "x") and (gensym "y"))
637 -- if variables didn't shaddow, the static gensym wouldn't be necessary
638 -- and we could reuse the original names (x and x).
639 --
640 -- do { x'1 <- gensym "x"
641 --    ; x'2 <- gensym "x"   
642 --    ; doE [ BindSt (pvar x'1) [| f 1 |]
643 --          , BindSt (pvar x'2) [| f x |] 
644 --          , NoBindSt [| g x |] 
645 --          ]
646 --    }
647
648 -- The strategy is to translate a whole list of do-bindings by building a
649 -- bigger environment, and a bigger set of meta bindings 
650 -- (like:  x'1 <- gensym "x" ) and then combining these with the translations
651 -- of the expressions within the Do
652       
653 -----------------------------------------------------------------------------
654 -- The helper function repSts computes the translation of each sub expression
655 -- and a bunch of prefix bindings denoting the dynamic renaming.
656
657 repLSts :: [LStmt Name] -> DsM ([GenSymBind], [Core TH.StmtQ])
658 repLSts stmts = repSts (map unLoc stmts)
659
660 repSts :: [Stmt Name] -> DsM ([GenSymBind], [Core TH.StmtQ])
661 repSts (BindStmt p e _ _ : ss) =
662    do { e2 <- repLE e 
663       ; ss1 <- mkGenSyms (collectPatBinders p) 
664       ; addBinds ss1 $ do {
665       ; p1 <- repLP p; 
666       ; (ss2,zs) <- repSts ss
667       ; z <- repBindSt p1 e2
668       ; return (ss1++ss2, z : zs) }}
669 repSts (LetStmt bs : ss) =
670    do { (ss1,ds) <- repBinds bs
671       ; z <- repLetSt ds
672       ; (ss2,zs) <- addBinds ss1 (repSts ss)
673       ; return (ss1++ss2, z : zs) } 
674 repSts (ExprStmt e _ _ : ss) =       
675    do { e2 <- repLE e
676       ; z <- repNoBindSt e2 
677       ; (ss2,zs) <- repSts ss
678       ; return (ss2, z : zs) }
679 repSts []    = return ([],[])
680 repSts other = notHandled "Exotic statement" (ppr other)
681
682
683 -----------------------------------------------------------
684 --                      Bindings
685 -----------------------------------------------------------
686
687 repBinds :: HsLocalBinds Name -> DsM ([GenSymBind], Core [TH.DecQ]) 
688 repBinds EmptyLocalBinds
689   = do  { core_list <- coreList decQTyConName []
690         ; return ([], core_list) }
691
692 repBinds b@(HsIPBinds _) = notHandled "Implicit parameters" (ppr b)
693
694 repBinds (HsValBinds decs)
695  = do   { let { bndrs = map unLoc (collectHsValBinders decs) }
696                 -- No need to worrry about detailed scopes within
697                 -- the binding group, because we are talking Names
698                 -- here, so we can safely treat it as a mutually 
699                 -- recursive group
700         ; ss        <- mkGenSyms bndrs
701         ; prs       <- addBinds ss (rep_val_binds decs)
702         ; core_list <- coreList decQTyConName 
703                                 (de_loc (sort_by_loc prs))
704         ; return (ss, core_list) }
705
706 rep_val_binds :: HsValBinds Name -> DsM [(SrcSpan, Core TH.DecQ)]
707 -- Assumes: all the binders of the binding are alrady in the meta-env
708 rep_val_binds (ValBindsOut binds sigs)
709  = do { core1 <- rep_binds' (unionManyBags (map snd binds))
710       ; core2 <- rep_sigs' sigs
711       ; return (core1 ++ core2) }
712 rep_val_binds (ValBindsIn _ _)
713  = panic "rep_val_binds: ValBindsIn"
714
715 rep_binds :: LHsBinds Name -> DsM [Core TH.DecQ]
716 rep_binds binds = do { binds_w_locs <- rep_binds' binds
717                      ; return (de_loc (sort_by_loc binds_w_locs)) }
718
719 rep_binds' :: LHsBinds Name -> DsM [(SrcSpan, Core TH.DecQ)]
720 rep_binds' binds = mapM rep_bind (bagToList binds)
721
722 rep_bind :: LHsBind Name -> DsM (SrcSpan, Core TH.DecQ)
723 -- Assumes: all the binders of the binding are alrady in the meta-env
724
725 -- Note GHC treats declarations of a variable (not a pattern) 
726 -- e.g.  x = g 5 as a Fun MonoBinds. This is indicated by a single match 
727 -- with an empty list of patterns
728 rep_bind (L loc (FunBind { fun_id = fn, 
729                            fun_matches = MatchGroup [L _ (Match [] _ (GRHSs guards wheres))] _ }))
730  = do { (ss,wherecore) <- repBinds wheres
731         ; guardcore <- addBinds ss (repGuards guards)
732         ; fn'  <- lookupLBinder fn
733         ; p    <- repPvar fn'
734         ; ans  <- repVal p guardcore wherecore
735         ; ans' <- wrapGenSyns ss ans
736         ; return (loc, ans') }
737
738 rep_bind (L loc (FunBind { fun_id = fn, fun_matches = MatchGroup ms _ }))
739  =   do { ms1 <- mapM repClauseTup ms
740         ; fn' <- lookupLBinder fn
741         ; ans <- repFun fn' (nonEmptyCoreList ms1)
742         ; return (loc, ans) }
743
744 rep_bind (L loc (PatBind { pat_lhs = pat, pat_rhs = GRHSs guards wheres }))
745  =   do { patcore <- repLP pat 
746         ; (ss,wherecore) <- repBinds wheres
747         ; guardcore <- addBinds ss (repGuards guards)
748         ; ans  <- repVal patcore guardcore wherecore
749         ; ans' <- wrapGenSyns ss ans
750         ; return (loc, ans') }
751
752 rep_bind (L _ (VarBind { var_id = v, var_rhs = e}))
753  =   do { v' <- lookupBinder v 
754         ; e2 <- repLE e
755         ; x <- repNormal e2
756         ; patcore <- repPvar v'
757         ; empty_decls <- coreList decQTyConName [] 
758         ; ans <- repVal patcore x empty_decls
759         ; return (srcLocSpan (getSrcLoc v), ans) }
760
761 rep_bind (L _ (AbsBinds {})) = panic "rep_bind: AbsBinds"
762
763 -----------------------------------------------------------------------------
764 -- Since everything in a Bind is mutually recursive we need rename all
765 -- all the variables simultaneously. For example: 
766 -- [| AndMonoBinds (f x = x + g 2) (g x = f 1 + 2) |] would translate to
767 -- do { f'1 <- gensym "f"
768 --    ; g'2 <- gensym "g"
769 --    ; [ do { x'3 <- gensym "x"; fun f'1 [pvar x'3] [| x + g2 |]},
770 --        do { x'4 <- gensym "x"; fun g'2 [pvar x'4] [| f 1 + 2 |]}
771 --      ]}
772 -- This requires collecting the bindings (f'1 <- gensym "f"), and the 
773 -- environment ( f |-> f'1 ) from each binding, and then unioning them 
774 -- together. As we do this we collect GenSymBinds's which represent the renamed 
775 -- variables bound by the Bindings. In order not to lose track of these 
776 -- representations we build a shadow datatype MB with the same structure as 
777 -- MonoBinds, but which has slots for the representations
778
779
780 -----------------------------------------------------------------------------
781 -- GHC allows a more general form of lambda abstraction than specified
782 -- by Haskell 98. In particular it allows guarded lambda's like : 
783 -- (\  x | even x -> 0 | odd x -> 1) at the moment we can't represent this in
784 -- Haskell Template's Meta.Exp type so we punt if it isn't a simple thing like
785 -- (\ p1 .. pn -> exp) by causing an error.  
786
787 repLambda :: LMatch Name -> DsM (Core TH.ExpQ)
788 repLambda (L _ (Match ps _ (GRHSs [L _ (GRHS [] e)] EmptyLocalBinds)))
789  = do { let bndrs = collectPatsBinders ps ;
790       ; ss  <- mkGenSyms bndrs
791       ; lam <- addBinds ss (
792                 do { xs <- repLPs ps; body <- repLE e; repLam xs body })
793       ; wrapGenSyns ss lam }
794
795 repLambda (L _ m) = notHandled "Guarded labmdas" (pprMatch (LambdaExpr :: HsMatchContext Name) m)
796
797   
798 -----------------------------------------------------------------------------
799 --                      Patterns
800 -- repP deals with patterns.  It assumes that we have already
801 -- walked over the pattern(s) once to collect the binders, and 
802 -- have extended the environment.  So every pattern-bound 
803 -- variable should already appear in the environment.
804
805 -- Process a list of patterns
806 repLPs :: [LPat Name] -> DsM (Core [TH.PatQ])
807 repLPs ps = do { ps' <- mapM repLP ps ;
808                  coreList patQTyConName ps' }
809
810 repLP :: LPat Name -> DsM (Core TH.PatQ)
811 repLP (L _ p) = repP p
812
813 repP :: Pat Name -> DsM (Core TH.PatQ)
814 repP (WildPat _)       = repPwild 
815 repP (LitPat l)        = do { l2 <- repLiteral l; repPlit l2 }
816 repP (VarPat x)        = do { x' <- lookupBinder x; repPvar x' }
817 repP (LazyPat p)       = do { p1 <- repLP p; repPtilde p1 }
818 repP (AsPat x p)       = do { x' <- lookupLBinder x; p1 <- repLP p; repPaspat x' p1 }
819 repP (ParPat p)        = repLP p 
820 repP (ListPat ps _)    = do { qs <- repLPs ps; repPlist qs }
821 repP (TuplePat ps _ _) = do { qs <- repLPs ps; repPtup qs }
822 repP (ConPatIn dc details)
823  = do { con_str <- lookupLOcc dc
824       ; case details of
825          PrefixCon ps -> do { qs <- repLPs ps; repPcon con_str qs }
826          RecCon rec   -> do { let flds = rec_flds rec
827                             ; vs <- sequence $ map lookupLOcc (map hsRecFieldId flds)
828                             ; ps <- sequence $ map repLP (map hsRecFieldArg flds)
829                             ; fps <- zipWithM (\x y -> rep2 fieldPatName [unC x,unC y]) vs ps
830                             ; fps' <- coreList fieldPatQTyConName fps
831                             ; repPrec con_str fps' }
832          InfixCon p1 p2 -> do { p1' <- repLP p1;
833                                 p2' <- repLP p2;
834                                 repPinfix p1' con_str p2' }
835    }
836 repP (NPat l Nothing _)  = do { a <- repOverloadedLiteral l; repPlit a }
837 repP p@(NPat _ (Just _) _) = notHandled "Negative overloaded patterns" (ppr p)
838 repP p@(SigPatIn {})  = notHandled "Type signatures in patterns" (ppr p)
839         -- The problem is to do with scoped type variables.
840         -- To implement them, we have to implement the scoping rules
841         -- here in DsMeta, and I don't want to do that today!
842         --       do { p' <- repLP p; t' <- repLTy t; repPsig p' t' }
843         --      repPsig :: Core TH.PatQ -> Core TH.TypeQ -> DsM (Core TH.PatQ)
844         --      repPsig (MkC p) (MkC t) = rep2 sigPName [p, t]
845
846 repP other = notHandled "Exotic pattern" (ppr other)
847
848 ----------------------------------------------------------
849 -- Declaration ordering helpers
850
851 sort_by_loc :: [(SrcSpan, a)] -> [(SrcSpan, a)]
852 sort_by_loc xs = sortBy comp xs
853     where comp x y = compare (fst x) (fst y)
854
855 de_loc :: [(a, b)] -> [b]
856 de_loc = map snd
857
858 ----------------------------------------------------------
859 --      The meta-environment
860
861 -- A name/identifier association for fresh names of locally bound entities
862 type GenSymBind = (Name, Id)    -- Gensym the string and bind it to the Id
863                                 -- I.e.         (x, x_id) means
864                                 --      let x_id = gensym "x" in ...
865
866 -- Generate a fresh name for a locally bound entity
867
868 mkGenSyms :: [Name] -> DsM [GenSymBind]
869 -- We can use the existing name.  For example:
870 --      [| \x_77 -> x_77 + x_77 |]
871 -- desugars to
872 --      do { x_77 <- genSym "x"; .... }
873 -- We use the same x_77 in the desugared program, but with the type Bndr
874 -- instead of Int
875 --
876 -- We do make it an Internal name, though (hence localiseName)
877 --
878 -- Nevertheless, it's monadic because we have to generate nameTy
879 mkGenSyms ns = do { var_ty <- lookupType nameTyConName
880                   ; return [(nm, mkLocalId (localiseName nm) var_ty) | nm <- ns] }
881
882              
883 addBinds :: [GenSymBind] -> DsM a -> DsM a
884 -- Add a list of fresh names for locally bound entities to the 
885 -- meta environment (which is part of the state carried around 
886 -- by the desugarer monad) 
887 addBinds bs m = dsExtendMetaEnv (mkNameEnv [(n,Bound id) | (n,id) <- bs]) m
888
889 -- Look up a locally bound name
890 --
891 lookupLBinder :: Located Name -> DsM (Core TH.Name)
892 lookupLBinder (L _ n) = lookupBinder n
893
894 lookupBinder :: Name -> DsM (Core TH.Name)
895 lookupBinder n 
896   = do { mb_val <- dsLookupMetaEnv n;
897          case mb_val of
898             Just (Bound x) -> return (coreVar x)
899             _              -> failWithDs msg }
900   where
901     msg = ptext (sLit "DsMeta: failed binder lookup when desugaring a TH bracket:") <+> ppr n
902
903 -- Look up a name that is either locally bound or a global name
904 --
905 --  * If it is a global name, generate the "original name" representation (ie,
906 --   the <module>:<name> form) for the associated entity
907 --
908 lookupLOcc :: Located Name -> DsM (Core TH.Name)
909 -- Lookup an occurrence; it can't be a splice.
910 -- Use the in-scope bindings if they exist
911 lookupLOcc (L _ n) = lookupOcc n
912
913 lookupOcc :: Name -> DsM (Core TH.Name)
914 lookupOcc n
915   = do {  mb_val <- dsLookupMetaEnv n ;
916           case mb_val of
917                 Nothing         -> globalVar n
918                 Just (Bound x)  -> return (coreVar x)
919                 Just (Splice _) -> pprPanic "repE:lookupOcc" (ppr n) 
920     }
921
922 lookupTvOcc :: Name -> DsM (Core TH.Name)
923 -- Type variables can't be staged and are not lexically scoped in TH
924 lookupTvOcc n   
925   = do {  mb_val <- dsLookupMetaEnv n ;
926           case mb_val of
927                 Just (Bound x)  -> return (coreVar x)
928                 _               -> failWithDs msg
929     }
930   where
931     msg = vcat  [ ptext (sLit "Illegal lexically-scoped type variable") <+> quotes (ppr n)
932                 , ptext (sLit "Lexically scoped type variables are not supported by Template Haskell") ]
933
934 globalVar :: Name -> DsM (Core TH.Name)
935 -- Not bound by the meta-env
936 -- Could be top-level; or could be local
937 --      f x = $(g [| x |])
938 -- Here the x will be local
939 globalVar name
940   | isExternalName name
941   = do  { MkC mod <- coreStringLit name_mod
942         ; MkC pkg <- coreStringLit name_pkg
943         ; MkC occ <- occNameLit name
944         ; rep2 mk_varg [pkg,mod,occ] }
945   | otherwise
946   = do  { MkC occ <- occNameLit name
947         ; MkC uni <- coreIntLit (getKey (getUnique name))
948         ; rep2 mkNameLName [occ,uni] }
949   where
950       mod = nameModule name
951       name_mod = moduleNameString (moduleName mod)
952       name_pkg = packageIdString (modulePackageId mod)
953       name_occ = nameOccName name
954       mk_varg | OccName.isDataOcc name_occ = mkNameG_dName
955               | OccName.isVarOcc  name_occ = mkNameG_vName
956               | OccName.isTcOcc   name_occ = mkNameG_tcName
957               | otherwise                  = pprPanic "DsMeta.globalVar" (ppr name)
958
959 lookupType :: Name      -- Name of type constructor (e.g. TH.ExpQ)
960            -> DsM Type  -- The type
961 lookupType tc_name = do { tc <- dsLookupTyCon tc_name ;
962                           return (mkTyConApp tc []) }
963
964 wrapGenSyns :: [GenSymBind] 
965             -> Core (TH.Q a) -> DsM (Core (TH.Q a))
966 -- wrapGenSyns [(nm1,id1), (nm2,id2)] y 
967 --      --> bindQ (gensym nm1) (\ id1 -> 
968 --          bindQ (gensym nm2 (\ id2 -> 
969 --          y))
970
971 wrapGenSyns binds body@(MkC b)
972   = do  { var_ty <- lookupType nameTyConName
973         ; go var_ty binds }
974   where
975     [elt_ty] = tcTyConAppArgs (exprType b) 
976         -- b :: Q a, so we can get the type 'a' by looking at the
977         -- argument type. NB: this relies on Q being a data/newtype,
978         -- not a type synonym
979
980     go _ [] = return body
981     go var_ty ((name,id) : binds)
982       = do { MkC body'  <- go var_ty binds
983            ; lit_str    <- occNameLit name
984            ; gensym_app <- repGensym lit_str
985            ; repBindQ var_ty elt_ty 
986                       gensym_app (MkC (Lam id body')) }
987
988 -- Just like wrapGenSym, but don't actually do the gensym
989 -- Instead use the existing name:
990 --      let x = "x" in ...
991 -- Only used for [Decl], and for the class ops in class 
992 -- and instance decls
993 wrapNongenSyms :: [GenSymBind] -> Core a -> DsM (Core a)
994 wrapNongenSyms binds (MkC body)
995   = do { binds' <- mapM do_one binds ;
996          return (MkC (mkLets binds' body)) }
997   where
998     do_one (name,id) 
999         = do { MkC lit_str <- occNameLit name
1000              ; MkC var <- rep2 mkNameName [lit_str]
1001              ; return (NonRec id var) }
1002
1003 occNameLit :: Name -> DsM (Core String)
1004 occNameLit n = coreStringLit (occNameString (nameOccName n))
1005
1006
1007 -- %*********************************************************************
1008 -- %*                                                                   *
1009 --              Constructing code
1010 -- %*                                                                   *
1011 -- %*********************************************************************
1012
1013 -----------------------------------------------------------------------------
1014 -- PHANTOM TYPES for consistency. In order to make sure we do this correct 
1015 -- we invent a new datatype which uses phantom types.
1016
1017 newtype Core a = MkC CoreExpr
1018 unC :: Core a -> CoreExpr
1019 unC (MkC x) = x
1020
1021 rep2 :: Name -> [ CoreExpr ] -> DsM (Core a)
1022 rep2 n xs = do { id <- dsLookupGlobalId n
1023                ; return (MkC (foldl App (Var id) xs)) }
1024
1025 -- Then we make "repConstructors" which use the phantom types for each of the
1026 -- smart constructors of the Meta.Meta datatypes.
1027
1028
1029 -- %*********************************************************************
1030 -- %*                                                                   *
1031 --              The 'smart constructors'
1032 -- %*                                                                   *
1033 -- %*********************************************************************
1034
1035 --------------- Patterns -----------------
1036 repPlit   :: Core TH.Lit -> DsM (Core TH.PatQ) 
1037 repPlit (MkC l) = rep2 litPName [l]
1038
1039 repPvar :: Core TH.Name -> DsM (Core TH.PatQ)
1040 repPvar (MkC s) = rep2 varPName [s]
1041
1042 repPtup :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
1043 repPtup (MkC ps) = rep2 tupPName [ps]
1044
1045 repPcon   :: Core TH.Name -> Core [TH.PatQ] -> DsM (Core TH.PatQ)
1046 repPcon (MkC s) (MkC ps) = rep2 conPName [s, ps]
1047
1048 repPrec   :: Core TH.Name -> Core [(TH.Name,TH.PatQ)] -> DsM (Core TH.PatQ)
1049 repPrec (MkC c) (MkC rps) = rep2 recPName [c,rps]
1050
1051 repPinfix :: Core TH.PatQ -> Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ)
1052 repPinfix (MkC p1) (MkC n) (MkC p2) = rep2 infixPName [p1, n, p2]
1053
1054 repPtilde :: Core TH.PatQ -> DsM (Core TH.PatQ)
1055 repPtilde (MkC p) = rep2 tildePName [p]
1056
1057 repPaspat :: Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ)
1058 repPaspat (MkC s) (MkC p) = rep2 asPName [s, p]
1059
1060 repPwild  :: DsM (Core TH.PatQ)
1061 repPwild = rep2 wildPName []
1062
1063 repPlist :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
1064 repPlist (MkC ps) = rep2 listPName [ps]
1065
1066 --------------- Expressions -----------------
1067 repVarOrCon :: Name -> Core TH.Name -> DsM (Core TH.ExpQ)
1068 repVarOrCon vc str | isDataOcc (nameOccName vc) = repCon str
1069                    | otherwise                  = repVar str
1070
1071 repVar :: Core TH.Name -> DsM (Core TH.ExpQ)
1072 repVar (MkC s) = rep2 varEName [s] 
1073
1074 repCon :: Core TH.Name -> DsM (Core TH.ExpQ)
1075 repCon (MkC s) = rep2 conEName [s] 
1076
1077 repLit :: Core TH.Lit -> DsM (Core TH.ExpQ)
1078 repLit (MkC c) = rep2 litEName [c] 
1079
1080 repApp :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1081 repApp (MkC x) (MkC y) = rep2 appEName [x,y] 
1082
1083 repLam :: Core [TH.PatQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1084 repLam (MkC ps) (MkC e) = rep2 lamEName [ps, e]
1085
1086 repTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
1087 repTup (MkC es) = rep2 tupEName [es]
1088
1089 repCond :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1090 repCond (MkC x) (MkC y) (MkC z) =  rep2 condEName [x,y,z] 
1091
1092 repLetE :: Core [TH.DecQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1093 repLetE (MkC ds) (MkC e) = rep2 letEName [ds, e] 
1094
1095 repCaseE :: Core TH.ExpQ -> Core [TH.MatchQ] -> DsM( Core TH.ExpQ)
1096 repCaseE (MkC e) (MkC ms) = rep2 caseEName [e, ms]
1097
1098 repDoE :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ)
1099 repDoE (MkC ss) = rep2 doEName [ss]
1100
1101 repComp :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ)
1102 repComp (MkC ss) = rep2 compEName [ss]
1103
1104 repListExp :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
1105 repListExp (MkC es) = rep2 listEName [es]
1106
1107 repSigExp :: Core TH.ExpQ -> Core TH.TypeQ -> DsM (Core TH.ExpQ)
1108 repSigExp (MkC e) (MkC t) = rep2 sigEName [e,t]
1109
1110 repRecCon :: Core TH.Name -> Core [TH.Q TH.FieldExp]-> DsM (Core TH.ExpQ)
1111 repRecCon (MkC c) (MkC fs) = rep2 recConEName [c,fs]
1112
1113 repRecUpd :: Core TH.ExpQ -> Core [TH.Q TH.FieldExp] -> DsM (Core TH.ExpQ)
1114 repRecUpd (MkC e) (MkC fs) = rep2 recUpdEName [e,fs]
1115
1116 repFieldExp :: Core TH.Name -> Core TH.ExpQ -> DsM (Core (TH.Q TH.FieldExp))
1117 repFieldExp (MkC n) (MkC x) = rep2 fieldExpName [n,x]
1118
1119 repInfixApp :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1120 repInfixApp (MkC x) (MkC y) (MkC z) = rep2 infixAppName [x,y,z]
1121
1122 repSectionL :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1123 repSectionL (MkC x) (MkC y) = rep2 sectionLName [x,y]
1124
1125 repSectionR :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1126 repSectionR (MkC x) (MkC y) = rep2 sectionRName [x,y]
1127
1128 ------------ Right hand sides (guarded expressions) ----
1129 repGuarded :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.BodyQ)
1130 repGuarded (MkC pairs) = rep2 guardedBName [pairs]
1131
1132 repNormal :: Core TH.ExpQ -> DsM (Core TH.BodyQ)
1133 repNormal (MkC e) = rep2 normalBName [e]
1134
1135 ------------ Guards ----
1136 repLNormalGE :: LHsExpr Name -> LHsExpr Name -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
1137 repLNormalGE g e = do g' <- repLE g
1138                       e' <- repLE e
1139                       repNormalGE g' e'
1140
1141 repNormalGE :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
1142 repNormalGE (MkC g) (MkC e) = rep2 normalGEName [g, e]
1143
1144 repPatGE :: Core [TH.StmtQ] -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
1145 repPatGE (MkC ss) (MkC e) = rep2 patGEName [ss, e]
1146
1147 ------------- Stmts -------------------
1148 repBindSt :: Core TH.PatQ -> Core TH.ExpQ -> DsM (Core TH.StmtQ)
1149 repBindSt (MkC p) (MkC e) = rep2 bindSName [p,e]
1150
1151 repLetSt :: Core [TH.DecQ] -> DsM (Core TH.StmtQ)
1152 repLetSt (MkC ds) = rep2 letSName [ds]
1153
1154 repNoBindSt :: Core TH.ExpQ -> DsM (Core TH.StmtQ)
1155 repNoBindSt (MkC e) = rep2 noBindSName [e]
1156
1157 -------------- Range (Arithmetic sequences) -----------
1158 repFrom :: Core TH.ExpQ -> DsM (Core TH.ExpQ)
1159 repFrom (MkC x) = rep2 fromEName [x]
1160
1161 repFromThen :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1162 repFromThen (MkC x) (MkC y) = rep2 fromThenEName [x,y]
1163
1164 repFromTo :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1165 repFromTo (MkC x) (MkC y) = rep2 fromToEName [x,y]
1166
1167 repFromThenTo :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1168 repFromThenTo (MkC x) (MkC y) (MkC z) = rep2 fromThenToEName [x,y,z]
1169
1170 ------------ Match and Clause Tuples -----------
1171 repMatch :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.MatchQ)
1172 repMatch (MkC p) (MkC bod) (MkC ds) = rep2 matchName [p, bod, ds]
1173
1174 repClause :: Core [TH.PatQ] -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.ClauseQ)
1175 repClause (MkC ps) (MkC bod) (MkC ds) = rep2 clauseName [ps, bod, ds]
1176
1177 -------------- Dec -----------------------------
1178 repVal :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ)
1179 repVal (MkC p) (MkC b) (MkC ds) = rep2 valDName [p, b, ds]
1180
1181 repFun :: Core TH.Name -> Core [TH.ClauseQ] -> DsM (Core TH.DecQ)  
1182 repFun (MkC nm) (MkC b) = rep2 funDName [nm, b]
1183
1184 repData :: Core TH.CxtQ -> Core TH.Name -> Core [TH.Name] -> Core [TH.ConQ] -> Core [TH.Name] -> DsM (Core TH.DecQ)
1185 repData (MkC cxt) (MkC nm) (MkC tvs) (MkC cons) (MkC derivs)
1186     = rep2 dataDName [cxt, nm, tvs, cons, derivs]
1187
1188 repNewtype :: Core TH.CxtQ -> Core TH.Name -> Core [TH.Name] -> Core TH.ConQ -> Core [TH.Name] -> DsM (Core TH.DecQ)
1189 repNewtype (MkC cxt) (MkC nm) (MkC tvs) (MkC con) (MkC derivs)
1190     = rep2 newtypeDName [cxt, nm, tvs, con, derivs]
1191
1192 repTySyn :: Core TH.Name -> Core [TH.Name] -> Core TH.TypeQ -> DsM (Core TH.DecQ)
1193 repTySyn (MkC nm) (MkC tvs) (MkC rhs) = rep2 tySynDName [nm, tvs, rhs]
1194
1195 repInst :: Core TH.CxtQ -> Core TH.TypeQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ)
1196 repInst (MkC cxt) (MkC ty) (MkC ds) = rep2 instanceDName [cxt, ty, ds]
1197
1198 repClass :: Core TH.CxtQ -> Core TH.Name -> Core [TH.Name] -> Core [TH.FunDep] -> Core [TH.DecQ] -> DsM (Core TH.DecQ)
1199 repClass (MkC cxt) (MkC cls) (MkC tvs) (MkC fds) (MkC ds) = rep2 classDName [cxt, cls, tvs, fds, ds]
1200
1201 repFunDep :: Core [TH.Name] -> Core [TH.Name] -> DsM (Core TH.FunDep)
1202 repFunDep (MkC xs) (MkC ys) = rep2 funDepName [xs, ys]
1203
1204 repProto :: Core TH.Name -> Core TH.TypeQ -> DsM (Core TH.DecQ)
1205 repProto (MkC s) (MkC ty) = rep2 sigDName [s, ty]
1206
1207 repCtxt :: Core [TH.TypeQ] -> DsM (Core TH.CxtQ)
1208 repCtxt (MkC tys) = rep2 cxtName [tys]
1209
1210 repConstr :: Core TH.Name -> HsConDeclDetails Name
1211           -> DsM (Core TH.ConQ)
1212 repConstr con (PrefixCon ps)
1213     = do arg_tys  <- mapM repBangTy ps
1214          arg_tys1 <- coreList strictTypeQTyConName arg_tys
1215          rep2 normalCName [unC con, unC arg_tys1]
1216 repConstr con (RecCon ips)
1217     = do arg_vs   <- mapM lookupLOcc (map cd_fld_name ips)
1218          arg_tys  <- mapM repBangTy (map cd_fld_type ips)
1219          arg_vtys <- zipWithM (\x y -> rep2 varStrictTypeName [unC x, unC y])
1220                               arg_vs arg_tys
1221          arg_vtys' <- coreList varStrictTypeQTyConName arg_vtys
1222          rep2 recCName [unC con, unC arg_vtys']
1223 repConstr con (InfixCon st1 st2)
1224     = do arg1 <- repBangTy st1
1225          arg2 <- repBangTy st2
1226          rep2 infixCName [unC arg1, unC con, unC arg2]
1227
1228 ------------ Types -------------------
1229
1230 repTForall :: Core [TH.Name] -> Core TH.CxtQ -> Core TH.TypeQ -> DsM (Core TH.TypeQ)
1231 repTForall (MkC tvars) (MkC ctxt) (MkC ty)
1232     = rep2 forallTName [tvars, ctxt, ty]
1233
1234 repTvar :: Core TH.Name -> DsM (Core TH.TypeQ)
1235 repTvar (MkC s) = rep2 varTName [s]
1236
1237 repTapp :: Core TH.TypeQ -> Core TH.TypeQ -> DsM (Core TH.TypeQ)
1238 repTapp (MkC t1) (MkC t2) = rep2 appTName [t1,t2]
1239
1240 repTapps :: Core TH.TypeQ -> [Core TH.TypeQ] -> DsM (Core TH.TypeQ)
1241 repTapps f []     = return f
1242 repTapps f (t:ts) = do { f1 <- repTapp f t; repTapps f1 ts }
1243
1244 --------- Type constructors --------------
1245
1246 repNamedTyCon :: Core TH.Name -> DsM (Core TH.TypeQ)
1247 repNamedTyCon (MkC s) = rep2 conTName [s]
1248
1249 repTupleTyCon :: Int -> DsM (Core TH.TypeQ)
1250 -- Note: not Core Int; it's easier to be direct here
1251 repTupleTyCon i = rep2 tupleTName [mkIntExpr (fromIntegral i)]
1252
1253 repArrowTyCon :: DsM (Core TH.TypeQ)
1254 repArrowTyCon = rep2 arrowTName []
1255
1256 repListTyCon :: DsM (Core TH.TypeQ)
1257 repListTyCon = rep2 listTName []
1258
1259
1260 ----------------------------------------------------------
1261 --              Literals
1262
1263 repLiteral :: HsLit -> DsM (Core TH.Lit)
1264 repLiteral lit 
1265   = do lit' <- case lit of
1266                    HsIntPrim i    -> mk_integer i
1267                    HsWordPrim w   -> mk_integer w
1268                    HsInt i        -> mk_integer i
1269                    HsFloatPrim r  -> mk_rational r
1270                    HsDoublePrim r -> mk_rational r
1271                    _ -> return lit
1272        lit_expr <- dsLit lit'
1273        case mb_lit_name of
1274           Just lit_name -> rep2 lit_name [lit_expr]
1275           Nothing -> notHandled "Exotic literal" (ppr lit)
1276   where
1277     mb_lit_name = case lit of
1278                  HsInteger _ _  -> Just integerLName
1279                  HsInt     _    -> Just integerLName
1280                  HsIntPrim _    -> Just intPrimLName
1281                  HsWordPrim _   -> Just wordPrimLName
1282                  HsFloatPrim _  -> Just floatPrimLName
1283                  HsDoublePrim _ -> Just doublePrimLName
1284                  HsChar _       -> Just charLName
1285                  HsString _     -> Just stringLName
1286                  HsRat _ _      -> Just rationalLName
1287                  _              -> Nothing
1288
1289 mk_integer :: Integer -> DsM HsLit
1290 mk_integer  i = do integer_ty <- lookupType integerTyConName
1291                    return $ HsInteger i integer_ty
1292 mk_rational :: Rational -> DsM HsLit
1293 mk_rational r = do rat_ty <- lookupType rationalTyConName
1294                    return $ HsRat r rat_ty
1295 mk_string :: FastString -> DsM HsLit
1296 mk_string s = return $ HsString s
1297
1298 repOverloadedLiteral :: HsOverLit Name -> DsM (Core TH.Lit)
1299 repOverloadedLiteral (OverLit { ol_val = val})
1300   = do { lit <- mk_lit val; repLiteral lit }
1301         -- The type Rational will be in the environment, becuase 
1302         -- the smart constructor 'TH.Syntax.rationalL' uses it in its type,
1303         -- and rationalL is sucked in when any TH stuff is used
1304
1305 mk_lit (HsIntegral i)   = mk_integer  i
1306 mk_lit (HsFractional f) = mk_rational f
1307 mk_lit (HsIsString s)   = mk_string   s
1308               
1309 --------------- Miscellaneous -------------------
1310
1311 repGensym :: Core String -> DsM (Core (TH.Q TH.Name))
1312 repGensym (MkC lit_str) = rep2 newNameName [lit_str]
1313
1314 repBindQ :: Type -> Type        -- a and b
1315          -> Core (TH.Q a) -> Core (a -> TH.Q b) -> DsM (Core (TH.Q b))
1316 repBindQ ty_a ty_b (MkC x) (MkC y) 
1317   = rep2 bindQName [Type ty_a, Type ty_b, x, y] 
1318
1319 repSequenceQ :: Type -> Core [TH.Q a] -> DsM (Core (TH.Q [a]))
1320 repSequenceQ ty_a (MkC list)
1321   = rep2 sequenceQName [Type ty_a, list]
1322
1323 ------------ Lists and Tuples -------------------
1324 -- turn a list of patterns into a single pattern matching a list
1325
1326 coreList :: Name        -- Of the TyCon of the element type
1327          -> [Core a] -> DsM (Core [a])
1328 coreList tc_name es 
1329   = do { elt_ty <- lookupType tc_name; return (coreList' elt_ty es) }
1330
1331 coreList' :: Type       -- The element type
1332           -> [Core a] -> Core [a]
1333 coreList' elt_ty es = MkC (mkListExpr elt_ty (map unC es ))
1334
1335 nonEmptyCoreList :: [Core a] -> Core [a]
1336   -- The list must be non-empty so we can get the element type
1337   -- Otherwise use coreList
1338 nonEmptyCoreList []           = panic "coreList: empty argument"
1339 nonEmptyCoreList xs@(MkC x:_) = MkC (mkListExpr (exprType x) (map unC xs))
1340
1341 coreStringLit :: String -> DsM (Core String)
1342 coreStringLit s = do { z <- mkStringExpr s; return(MkC z) }
1343
1344 coreIntLit :: Int -> DsM (Core Int)
1345 coreIntLit i = return (MkC (mkIntExpr (fromIntegral i)))
1346
1347 coreVar :: Id -> Core TH.Name   -- The Id has type Name
1348 coreVar id = MkC (Var id)
1349
1350 ----------------- Failure -----------------------
1351 notHandled :: String -> SDoc -> DsM a
1352 notHandled what doc = failWithDs msg
1353   where
1354     msg = hang (text what <+> ptext (sLit "not (yet) handled by Template Haskell")) 
1355              2 doc
1356
1357
1358 -- %************************************************************************
1359 -- %*                                                                   *
1360 --              The known-key names for Template Haskell
1361 -- %*                                                                   *
1362 -- %************************************************************************
1363
1364 -- To add a name, do three things
1365 -- 
1366 --  1) Allocate a key
1367 --  2) Make a "Name"
1368 --  3) Add the name to knownKeyNames
1369
1370 templateHaskellNames :: [Name]
1371 -- The names that are implicitly mentioned by ``bracket''
1372 -- Should stay in sync with the import list of DsMeta
1373
1374 templateHaskellNames = [
1375     returnQName, bindQName, sequenceQName, newNameName, liftName,
1376     mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName, mkNameLName, 
1377
1378     -- Lit
1379     charLName, stringLName, integerLName, intPrimLName, wordPrimLName,
1380     floatPrimLName, doublePrimLName, rationalLName,
1381     -- Pat
1382     litPName, varPName, tupPName, conPName, tildePName, infixPName,
1383     asPName, wildPName, recPName, listPName, sigPName,
1384     -- FieldPat
1385     fieldPatName,
1386     -- Match
1387     matchName,
1388     -- Clause
1389     clauseName,
1390     -- Exp
1391     varEName, conEName, litEName, appEName, infixEName,
1392     infixAppName, sectionLName, sectionRName, lamEName, tupEName,
1393     condEName, letEName, caseEName, doEName, compEName,
1394     fromEName, fromThenEName, fromToEName, fromThenToEName,
1395     listEName, sigEName, recConEName, recUpdEName,
1396     -- FieldExp
1397     fieldExpName,
1398     -- Body
1399     guardedBName, normalBName,
1400     -- Guard
1401     normalGEName, patGEName,
1402     -- Stmt
1403     bindSName, letSName, noBindSName, parSName,
1404     -- Dec
1405     funDName, valDName, dataDName, newtypeDName, tySynDName,
1406     classDName, instanceDName, sigDName, forImpDName,
1407     -- Cxt
1408     cxtName,
1409     -- Strict
1410     isStrictName, notStrictName,
1411     -- Con
1412     normalCName, recCName, infixCName, forallCName,
1413     -- StrictType
1414     strictTypeName,
1415     -- VarStrictType
1416     varStrictTypeName,
1417     -- Type
1418     forallTName, varTName, conTName, appTName,
1419     tupleTName, arrowTName, listTName,
1420     -- Callconv
1421     cCallName, stdCallName,
1422     -- Safety
1423     unsafeName,
1424     safeName,
1425     threadsafeName,
1426     -- FunDep
1427     funDepName,
1428
1429     -- And the tycons
1430     qTyConName, nameTyConName, patTyConName, fieldPatTyConName, matchQTyConName,
1431     clauseQTyConName, expQTyConName, fieldExpTyConName, stmtQTyConName,
1432     decQTyConName, conQTyConName, strictTypeQTyConName,
1433     varStrictTypeQTyConName, typeQTyConName, expTyConName, decTyConName,
1434     typeTyConName, matchTyConName, clauseTyConName, patQTyConName,
1435     fieldPatQTyConName, fieldExpQTyConName, funDepTyConName,
1436
1437     -- Quasiquoting
1438     quoteExpName, quotePatName]
1439
1440 thSyn, thLib, qqLib :: Module
1441 thSyn = mkTHModule (fsLit "Language.Haskell.TH.Syntax")
1442 thLib = mkTHModule (fsLit "Language.Haskell.TH.Lib")
1443 qqLib = mkTHModule (fsLit "Language.Haskell.TH.Quote")
1444
1445 mkTHModule :: FastString -> Module
1446 mkTHModule m = mkModule thPackageId (mkModuleNameFS m)
1447
1448 libFun, libTc, thFun, thTc, qqFun :: FastString -> Unique -> Name
1449 libFun = mk_known_key_name OccName.varName thLib
1450 libTc  = mk_known_key_name OccName.tcName  thLib
1451 thFun  = mk_known_key_name OccName.varName thSyn
1452 thTc   = mk_known_key_name OccName.tcName  thSyn
1453 qqFun  = mk_known_key_name OccName.varName qqLib
1454
1455 -------------------- TH.Syntax -----------------------
1456 qTyConName, nameTyConName, fieldExpTyConName, patTyConName,
1457     fieldPatTyConName, expTyConName, decTyConName, typeTyConName,
1458     matchTyConName, clauseTyConName, funDepTyConName :: Name
1459 qTyConName        = thTc (fsLit "Q")            qTyConKey
1460 nameTyConName     = thTc (fsLit "Name")         nameTyConKey
1461 fieldExpTyConName = thTc (fsLit "FieldExp")     fieldExpTyConKey
1462 patTyConName      = thTc (fsLit "Pat")          patTyConKey
1463 fieldPatTyConName = thTc (fsLit "FieldPat")     fieldPatTyConKey
1464 expTyConName      = thTc (fsLit "Exp")          expTyConKey
1465 decTyConName      = thTc (fsLit "Dec")          decTyConKey
1466 typeTyConName     = thTc (fsLit "Type")         typeTyConKey
1467 matchTyConName    = thTc (fsLit "Match")        matchTyConKey
1468 clauseTyConName   = thTc (fsLit "Clause")       clauseTyConKey
1469 funDepTyConName   = thTc (fsLit "FunDep")       funDepTyConKey
1470
1471 returnQName, bindQName, sequenceQName, newNameName, liftName,
1472     mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName,
1473     mkNameLName :: Name
1474 returnQName   = thFun (fsLit "returnQ")   returnQIdKey
1475 bindQName     = thFun (fsLit "bindQ")     bindQIdKey
1476 sequenceQName = thFun (fsLit "sequenceQ") sequenceQIdKey
1477 newNameName    = thFun (fsLit "newName")   newNameIdKey
1478 liftName      = thFun (fsLit "lift")      liftIdKey
1479 mkNameName     = thFun (fsLit "mkName")     mkNameIdKey
1480 mkNameG_vName  = thFun (fsLit "mkNameG_v")  mkNameG_vIdKey
1481 mkNameG_dName  = thFun (fsLit "mkNameG_d")  mkNameG_dIdKey
1482 mkNameG_tcName = thFun (fsLit "mkNameG_tc") mkNameG_tcIdKey
1483 mkNameLName    = thFun (fsLit "mkNameL")    mkNameLIdKey
1484
1485
1486 -------------------- TH.Lib -----------------------
1487 -- data Lit = ...
1488 charLName, stringLName, integerLName, intPrimLName, wordPrimLName,
1489     floatPrimLName, doublePrimLName, rationalLName :: Name
1490 charLName       = libFun (fsLit "charL")       charLIdKey
1491 stringLName     = libFun (fsLit "stringL")     stringLIdKey
1492 integerLName    = libFun (fsLit "integerL")    integerLIdKey
1493 intPrimLName    = libFun (fsLit "intPrimL")    intPrimLIdKey
1494 wordPrimLName   = libFun (fsLit "wordPrimL")   wordPrimLIdKey
1495 floatPrimLName  = libFun (fsLit "floatPrimL")  floatPrimLIdKey
1496 doublePrimLName = libFun (fsLit "doublePrimL") doublePrimLIdKey
1497 rationalLName   = libFun (fsLit "rationalL")     rationalLIdKey
1498
1499 -- data Pat = ...
1500 litPName, varPName, tupPName, conPName, infixPName, tildePName,
1501     asPName, wildPName, recPName, listPName, sigPName :: Name
1502 litPName   = libFun (fsLit "litP")   litPIdKey
1503 varPName   = libFun (fsLit "varP")   varPIdKey
1504 tupPName   = libFun (fsLit "tupP")   tupPIdKey
1505 conPName   = libFun (fsLit "conP")   conPIdKey
1506 infixPName = libFun (fsLit "infixP") infixPIdKey
1507 tildePName = libFun (fsLit "tildeP") tildePIdKey
1508 asPName    = libFun (fsLit "asP")    asPIdKey
1509 wildPName  = libFun (fsLit "wildP")  wildPIdKey
1510 recPName   = libFun (fsLit "recP")   recPIdKey
1511 listPName  = libFun (fsLit "listP")  listPIdKey
1512 sigPName   = libFun (fsLit "sigP")   sigPIdKey
1513
1514 -- type FieldPat = ...
1515 fieldPatName :: Name
1516 fieldPatName = libFun (fsLit "fieldPat") fieldPatIdKey
1517
1518 -- data Match = ...
1519 matchName :: Name
1520 matchName = libFun (fsLit "match") matchIdKey
1521
1522 -- data Clause = ...
1523 clauseName :: Name
1524 clauseName = libFun (fsLit "clause") clauseIdKey
1525
1526 -- data Exp = ...
1527 varEName, conEName, litEName, appEName, infixEName, infixAppName,
1528     sectionLName, sectionRName, lamEName, tupEName, condEName,
1529     letEName, caseEName, doEName, compEName :: Name
1530 varEName        = libFun (fsLit "varE")        varEIdKey
1531 conEName        = libFun (fsLit "conE")        conEIdKey
1532 litEName        = libFun (fsLit "litE")        litEIdKey
1533 appEName        = libFun (fsLit "appE")        appEIdKey
1534 infixEName      = libFun (fsLit "infixE")      infixEIdKey
1535 infixAppName    = libFun (fsLit "infixApp")    infixAppIdKey
1536 sectionLName    = libFun (fsLit "sectionL")    sectionLIdKey
1537 sectionRName    = libFun (fsLit "sectionR")    sectionRIdKey
1538 lamEName        = libFun (fsLit "lamE")        lamEIdKey
1539 tupEName        = libFun (fsLit "tupE")        tupEIdKey
1540 condEName       = libFun (fsLit "condE")       condEIdKey
1541 letEName        = libFun (fsLit "letE")        letEIdKey
1542 caseEName       = libFun (fsLit "caseE")       caseEIdKey
1543 doEName         = libFun (fsLit "doE")         doEIdKey
1544 compEName       = libFun (fsLit "compE")       compEIdKey
1545 -- ArithSeq skips a level
1546 fromEName, fromThenEName, fromToEName, fromThenToEName :: Name
1547 fromEName       = libFun (fsLit "fromE")       fromEIdKey
1548 fromThenEName   = libFun (fsLit "fromThenE")   fromThenEIdKey
1549 fromToEName     = libFun (fsLit "fromToE")     fromToEIdKey
1550 fromThenToEName = libFun (fsLit "fromThenToE") fromThenToEIdKey
1551 -- end ArithSeq
1552 listEName, sigEName, recConEName, recUpdEName :: Name
1553 listEName       = libFun (fsLit "listE")       listEIdKey
1554 sigEName        = libFun (fsLit "sigE")        sigEIdKey
1555 recConEName     = libFun (fsLit "recConE")     recConEIdKey
1556 recUpdEName     = libFun (fsLit "recUpdE")     recUpdEIdKey
1557
1558 -- type FieldExp = ...
1559 fieldExpName :: Name
1560 fieldExpName = libFun (fsLit "fieldExp") fieldExpIdKey
1561
1562 -- data Body = ...
1563 guardedBName, normalBName :: Name
1564 guardedBName = libFun (fsLit "guardedB") guardedBIdKey
1565 normalBName  = libFun (fsLit "normalB")  normalBIdKey
1566
1567 -- data Guard = ...
1568 normalGEName, patGEName :: Name
1569 normalGEName = libFun (fsLit "normalGE") normalGEIdKey
1570 patGEName    = libFun (fsLit "patGE")    patGEIdKey
1571
1572 -- data Stmt = ...
1573 bindSName, letSName, noBindSName, parSName :: Name
1574 bindSName   = libFun (fsLit "bindS")   bindSIdKey
1575 letSName    = libFun (fsLit "letS")    letSIdKey
1576 noBindSName = libFun (fsLit "noBindS") noBindSIdKey
1577 parSName    = libFun (fsLit "parS")    parSIdKey
1578
1579 -- data Dec = ...
1580 funDName, valDName, dataDName, newtypeDName, tySynDName, classDName,
1581     instanceDName, sigDName, forImpDName :: Name
1582 funDName      = libFun (fsLit "funD")      funDIdKey
1583 valDName      = libFun (fsLit "valD")      valDIdKey
1584 dataDName     = libFun (fsLit "dataD")     dataDIdKey
1585 newtypeDName  = libFun (fsLit "newtypeD")  newtypeDIdKey
1586 tySynDName    = libFun (fsLit "tySynD")    tySynDIdKey
1587 classDName    = libFun (fsLit "classD")    classDIdKey
1588 instanceDName = libFun (fsLit "instanceD") instanceDIdKey
1589 sigDName      = libFun (fsLit "sigD")      sigDIdKey
1590 forImpDName   = libFun (fsLit "forImpD")   forImpDIdKey
1591
1592 -- type Ctxt = ...
1593 cxtName :: Name
1594 cxtName = libFun (fsLit "cxt") cxtIdKey
1595
1596 -- data Strict = ...
1597 isStrictName, notStrictName :: Name
1598 isStrictName      = libFun  (fsLit "isStrict")      isStrictKey
1599 notStrictName     = libFun  (fsLit "notStrict")     notStrictKey
1600
1601 -- data Con = ...
1602 normalCName, recCName, infixCName, forallCName :: Name
1603 normalCName = libFun (fsLit "normalC") normalCIdKey
1604 recCName    = libFun (fsLit "recC")    recCIdKey
1605 infixCName  = libFun (fsLit "infixC")  infixCIdKey
1606 forallCName  = libFun (fsLit "forallC")  forallCIdKey
1607
1608 -- type StrictType = ...
1609 strictTypeName :: Name
1610 strictTypeName    = libFun  (fsLit "strictType")    strictTKey
1611
1612 -- type VarStrictType = ...
1613 varStrictTypeName :: Name
1614 varStrictTypeName = libFun  (fsLit "varStrictType") varStrictTKey
1615
1616 -- data Type = ...
1617 forallTName, varTName, conTName, tupleTName, arrowTName,
1618     listTName, appTName :: Name
1619 forallTName = libFun (fsLit "forallT") forallTIdKey
1620 varTName    = libFun (fsLit "varT")    varTIdKey
1621 conTName    = libFun (fsLit "conT")    conTIdKey
1622 tupleTName  = libFun (fsLit "tupleT") tupleTIdKey
1623 arrowTName  = libFun (fsLit "arrowT") arrowTIdKey
1624 listTName   = libFun (fsLit "listT")  listTIdKey
1625 appTName    = libFun (fsLit "appT")    appTIdKey
1626
1627 -- data Callconv = ...
1628 cCallName, stdCallName :: Name
1629 cCallName = libFun (fsLit "cCall") cCallIdKey
1630 stdCallName = libFun (fsLit "stdCall") stdCallIdKey
1631
1632 -- data Safety = ...
1633 unsafeName, safeName, threadsafeName :: Name
1634 unsafeName     = libFun (fsLit "unsafe") unsafeIdKey
1635 safeName       = libFun (fsLit "safe") safeIdKey
1636 threadsafeName = libFun (fsLit "threadsafe") threadsafeIdKey
1637
1638 -- data FunDep = ...
1639 funDepName :: Name
1640 funDepName     = libFun (fsLit "funDep") funDepIdKey
1641
1642 matchQTyConName, clauseQTyConName, expQTyConName, stmtQTyConName,
1643     decQTyConName, conQTyConName, strictTypeQTyConName,
1644     varStrictTypeQTyConName, typeQTyConName, fieldExpQTyConName,
1645     patQTyConName, fieldPatQTyConName :: Name
1646 matchQTyConName         = libTc (fsLit "MatchQ")        matchQTyConKey
1647 clauseQTyConName        = libTc (fsLit "ClauseQ")       clauseQTyConKey
1648 expQTyConName           = libTc (fsLit "ExpQ")          expQTyConKey
1649 stmtQTyConName          = libTc (fsLit "StmtQ")         stmtQTyConKey
1650 decQTyConName           = libTc (fsLit "DecQ")          decQTyConKey
1651 conQTyConName           = libTc (fsLit "ConQ")          conQTyConKey
1652 strictTypeQTyConName    = libTc (fsLit "StrictTypeQ")    strictTypeQTyConKey
1653 varStrictTypeQTyConName = libTc (fsLit "VarStrictTypeQ") varStrictTypeQTyConKey
1654 typeQTyConName          = libTc (fsLit "TypeQ")          typeQTyConKey
1655 fieldExpQTyConName      = libTc (fsLit "FieldExpQ")      fieldExpQTyConKey
1656 patQTyConName           = libTc (fsLit "PatQ")           patQTyConKey
1657 fieldPatQTyConName      = libTc (fsLit "FieldPatQ")      fieldPatQTyConKey
1658
1659 -- quasiquoting
1660 quoteExpName, quotePatName :: Name
1661 quoteExpName        = qqFun (fsLit "quoteExp") quoteExpKey
1662 quotePatName        = qqFun (fsLit "quotePat") quotePatKey
1663
1664 -- TyConUniques available: 100-129
1665 -- Check in PrelNames if you want to change this
1666
1667 expTyConKey, matchTyConKey, clauseTyConKey, qTyConKey, expQTyConKey,
1668     decQTyConKey, patTyConKey, matchQTyConKey, clauseQTyConKey,
1669     stmtQTyConKey, conQTyConKey, typeQTyConKey, typeTyConKey,
1670     decTyConKey, varStrictTypeQTyConKey, strictTypeQTyConKey,
1671     fieldExpTyConKey, fieldPatTyConKey, nameTyConKey, patQTyConKey,
1672     fieldPatQTyConKey, fieldExpQTyConKey, funDepTyConKey :: Unique
1673 expTyConKey             = mkPreludeTyConUnique 100
1674 matchTyConKey           = mkPreludeTyConUnique 101
1675 clauseTyConKey          = mkPreludeTyConUnique 102
1676 qTyConKey               = mkPreludeTyConUnique 103
1677 expQTyConKey            = mkPreludeTyConUnique 104
1678 decQTyConKey            = mkPreludeTyConUnique 105
1679 patTyConKey             = mkPreludeTyConUnique 106
1680 matchQTyConKey          = mkPreludeTyConUnique 107
1681 clauseQTyConKey         = mkPreludeTyConUnique 108
1682 stmtQTyConKey           = mkPreludeTyConUnique 109
1683 conQTyConKey            = mkPreludeTyConUnique 110
1684 typeQTyConKey           = mkPreludeTyConUnique 111
1685 typeTyConKey            = mkPreludeTyConUnique 112
1686 decTyConKey             = mkPreludeTyConUnique 113
1687 varStrictTypeQTyConKey  = mkPreludeTyConUnique 114
1688 strictTypeQTyConKey     = mkPreludeTyConUnique 115
1689 fieldExpTyConKey        = mkPreludeTyConUnique 116
1690 fieldPatTyConKey        = mkPreludeTyConUnique 117
1691 nameTyConKey            = mkPreludeTyConUnique 118
1692 patQTyConKey            = mkPreludeTyConUnique 119
1693 fieldPatQTyConKey       = mkPreludeTyConUnique 120
1694 fieldExpQTyConKey       = mkPreludeTyConUnique 121
1695 funDepTyConKey          = mkPreludeTyConUnique 122
1696
1697 -- IdUniques available: 200-399
1698 -- If you want to change this, make sure you check in PrelNames
1699
1700 returnQIdKey, bindQIdKey, sequenceQIdKey, liftIdKey, newNameIdKey,
1701     mkNameIdKey, mkNameG_vIdKey, mkNameG_dIdKey, mkNameG_tcIdKey,
1702     mkNameLIdKey :: Unique
1703 returnQIdKey        = mkPreludeMiscIdUnique 200
1704 bindQIdKey          = mkPreludeMiscIdUnique 201
1705 sequenceQIdKey      = mkPreludeMiscIdUnique 202
1706 liftIdKey           = mkPreludeMiscIdUnique 203
1707 newNameIdKey         = mkPreludeMiscIdUnique 204
1708 mkNameIdKey          = mkPreludeMiscIdUnique 205
1709 mkNameG_vIdKey       = mkPreludeMiscIdUnique 206
1710 mkNameG_dIdKey       = mkPreludeMiscIdUnique 207
1711 mkNameG_tcIdKey      = mkPreludeMiscIdUnique 208
1712 mkNameLIdKey         = mkPreludeMiscIdUnique 209
1713
1714
1715 -- data Lit = ...
1716 charLIdKey, stringLIdKey, integerLIdKey, intPrimLIdKey, wordPrimLIdKey,
1717     floatPrimLIdKey, doublePrimLIdKey, rationalLIdKey :: Unique
1718 charLIdKey        = mkPreludeMiscIdUnique 210
1719 stringLIdKey      = mkPreludeMiscIdUnique 211
1720 integerLIdKey     = mkPreludeMiscIdUnique 212
1721 intPrimLIdKey     = mkPreludeMiscIdUnique 213
1722 wordPrimLIdKey    = mkPreludeMiscIdUnique 214
1723 floatPrimLIdKey   = mkPreludeMiscIdUnique 215
1724 doublePrimLIdKey  = mkPreludeMiscIdUnique 216
1725 rationalLIdKey    = mkPreludeMiscIdUnique 217
1726
1727 -- data Pat = ...
1728 litPIdKey, varPIdKey, tupPIdKey, conPIdKey, infixPIdKey, tildePIdKey,
1729     asPIdKey, wildPIdKey, recPIdKey, listPIdKey, sigPIdKey :: Unique
1730 litPIdKey         = mkPreludeMiscIdUnique 220
1731 varPIdKey         = mkPreludeMiscIdUnique 221
1732 tupPIdKey         = mkPreludeMiscIdUnique 222
1733 conPIdKey         = mkPreludeMiscIdUnique 223
1734 infixPIdKey       = mkPreludeMiscIdUnique 312
1735 tildePIdKey       = mkPreludeMiscIdUnique 224
1736 asPIdKey          = mkPreludeMiscIdUnique 225
1737 wildPIdKey        = mkPreludeMiscIdUnique 226
1738 recPIdKey         = mkPreludeMiscIdUnique 227
1739 listPIdKey        = mkPreludeMiscIdUnique 228
1740 sigPIdKey         = mkPreludeMiscIdUnique 229
1741
1742 -- type FieldPat = ...
1743 fieldPatIdKey :: Unique
1744 fieldPatIdKey       = mkPreludeMiscIdUnique 230
1745
1746 -- data Match = ...
1747 matchIdKey :: Unique
1748 matchIdKey          = mkPreludeMiscIdUnique 231
1749
1750 -- data Clause = ...
1751 clauseIdKey :: Unique
1752 clauseIdKey         = mkPreludeMiscIdUnique 232
1753
1754 -- data Exp = ...
1755 varEIdKey, conEIdKey, litEIdKey, appEIdKey, infixEIdKey, infixAppIdKey,
1756     sectionLIdKey, sectionRIdKey, lamEIdKey, tupEIdKey, condEIdKey,
1757     letEIdKey, caseEIdKey, doEIdKey, compEIdKey,
1758     fromEIdKey, fromThenEIdKey, fromToEIdKey, fromThenToEIdKey,
1759     listEIdKey, sigEIdKey, recConEIdKey, recUpdEIdKey :: Unique
1760 varEIdKey         = mkPreludeMiscIdUnique 240
1761 conEIdKey         = mkPreludeMiscIdUnique 241
1762 litEIdKey         = mkPreludeMiscIdUnique 242
1763 appEIdKey         = mkPreludeMiscIdUnique 243
1764 infixEIdKey       = mkPreludeMiscIdUnique 244
1765 infixAppIdKey       = mkPreludeMiscIdUnique 245
1766 sectionLIdKey       = mkPreludeMiscIdUnique 246
1767 sectionRIdKey       = mkPreludeMiscIdUnique 247
1768 lamEIdKey         = mkPreludeMiscIdUnique 248
1769 tupEIdKey         = mkPreludeMiscIdUnique 249
1770 condEIdKey        = mkPreludeMiscIdUnique 250
1771 letEIdKey         = mkPreludeMiscIdUnique 251
1772 caseEIdKey        = mkPreludeMiscIdUnique 252
1773 doEIdKey          = mkPreludeMiscIdUnique 253
1774 compEIdKey        = mkPreludeMiscIdUnique 254
1775 fromEIdKey        = mkPreludeMiscIdUnique 255
1776 fromThenEIdKey    = mkPreludeMiscIdUnique 256
1777 fromToEIdKey      = mkPreludeMiscIdUnique 257
1778 fromThenToEIdKey  = mkPreludeMiscIdUnique 258
1779 listEIdKey        = mkPreludeMiscIdUnique 259
1780 sigEIdKey         = mkPreludeMiscIdUnique 260
1781 recConEIdKey      = mkPreludeMiscIdUnique 261
1782 recUpdEIdKey      = mkPreludeMiscIdUnique 262
1783
1784 -- type FieldExp = ...
1785 fieldExpIdKey :: Unique
1786 fieldExpIdKey       = mkPreludeMiscIdUnique 265
1787
1788 -- data Body = ...
1789 guardedBIdKey, normalBIdKey :: Unique
1790 guardedBIdKey     = mkPreludeMiscIdUnique 266
1791 normalBIdKey      = mkPreludeMiscIdUnique 267
1792
1793 -- data Guard = ...
1794 normalGEIdKey, patGEIdKey :: Unique
1795 normalGEIdKey     = mkPreludeMiscIdUnique 310
1796 patGEIdKey        = mkPreludeMiscIdUnique 311
1797
1798 -- data Stmt = ...
1799 bindSIdKey, letSIdKey, noBindSIdKey, parSIdKey :: Unique
1800 bindSIdKey       = mkPreludeMiscIdUnique 268
1801 letSIdKey        = mkPreludeMiscIdUnique 269
1802 noBindSIdKey     = mkPreludeMiscIdUnique 270
1803 parSIdKey        = mkPreludeMiscIdUnique 271
1804
1805 -- data Dec = ...
1806 funDIdKey, valDIdKey, dataDIdKey, newtypeDIdKey, tySynDIdKey,
1807     classDIdKey, instanceDIdKey, sigDIdKey, forImpDIdKey :: Unique
1808 funDIdKey         = mkPreludeMiscIdUnique 272
1809 valDIdKey         = mkPreludeMiscIdUnique 273
1810 dataDIdKey        = mkPreludeMiscIdUnique 274
1811 newtypeDIdKey     = mkPreludeMiscIdUnique 275
1812 tySynDIdKey       = mkPreludeMiscIdUnique 276
1813 classDIdKey       = mkPreludeMiscIdUnique 277
1814 instanceDIdKey    = mkPreludeMiscIdUnique 278
1815 sigDIdKey         = mkPreludeMiscIdUnique 279
1816 forImpDIdKey      = mkPreludeMiscIdUnique 297
1817
1818 -- type Cxt = ...
1819 cxtIdKey :: Unique
1820 cxtIdKey            = mkPreludeMiscIdUnique 280
1821
1822 -- data Strict = ...
1823 isStrictKey, notStrictKey :: Unique
1824 isStrictKey         = mkPreludeMiscIdUnique 281
1825 notStrictKey        = mkPreludeMiscIdUnique 282
1826
1827 -- data Con = ...
1828 normalCIdKey, recCIdKey, infixCIdKey, forallCIdKey :: Unique
1829 normalCIdKey      = mkPreludeMiscIdUnique 283
1830 recCIdKey         = mkPreludeMiscIdUnique 284
1831 infixCIdKey       = mkPreludeMiscIdUnique 285
1832 forallCIdKey      = mkPreludeMiscIdUnique 288
1833
1834 -- type StrictType = ...
1835 strictTKey :: Unique
1836 strictTKey        = mkPreludeMiscIdUnique 286
1837
1838 -- type VarStrictType = ...
1839 varStrictTKey :: Unique
1840 varStrictTKey     = mkPreludeMiscIdUnique 287
1841
1842 -- data Type = ...
1843 forallTIdKey, varTIdKey, conTIdKey, tupleTIdKey, arrowTIdKey,
1844     listTIdKey, appTIdKey :: Unique
1845 forallTIdKey      = mkPreludeMiscIdUnique 290
1846 varTIdKey         = mkPreludeMiscIdUnique 291
1847 conTIdKey         = mkPreludeMiscIdUnique 292
1848 tupleTIdKey       = mkPreludeMiscIdUnique 294
1849 arrowTIdKey       = mkPreludeMiscIdUnique 295
1850 listTIdKey        = mkPreludeMiscIdUnique 296
1851 appTIdKey         = mkPreludeMiscIdUnique 293
1852
1853 -- data Callconv = ...
1854 cCallIdKey, stdCallIdKey :: Unique
1855 cCallIdKey      = mkPreludeMiscIdUnique 300
1856 stdCallIdKey    = mkPreludeMiscIdUnique 301
1857
1858 -- data Safety = ...
1859 unsafeIdKey, safeIdKey, threadsafeIdKey :: Unique
1860 unsafeIdKey     = mkPreludeMiscIdUnique 305
1861 safeIdKey       = mkPreludeMiscIdUnique 306
1862 threadsafeIdKey = mkPreludeMiscIdUnique 307
1863
1864 -- data FunDep = ...
1865 funDepIdKey :: Unique
1866 funDepIdKey = mkPreludeMiscIdUnique 320
1867
1868 -- quasiquoting
1869 quoteExpKey, quotePatKey :: Unique
1870 quoteExpKey = mkPreludeMiscIdUnique 321
1871 quotePatKey = mkPreludeMiscIdUnique 322
1872