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