Make DsMeta almost warning-free
[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   = do return $ HsString s
1297
1298 repOverloadedLiteral :: HsOverLit Name -> DsM (Core TH.Lit)
1299 repOverloadedLiteral (HsIntegral i _ _)   = do { lit <- mk_integer  i; repLiteral lit }
1300 repOverloadedLiteral (HsFractional f _ _) = do { lit <- mk_rational f; repLiteral lit }
1301 repOverloadedLiteral (HsIsString s _ _)   = do { lit <- mk_string   s; repLiteral lit }
1302         -- The type Rational will be in the environment, becuase 
1303         -- the smart constructor 'TH.Syntax.rationalL' uses it in its type,
1304         -- and rationalL is sucked in when any TH stuff is used
1305               
1306 --------------- Miscellaneous -------------------
1307
1308 repGensym :: Core String -> DsM (Core (TH.Q TH.Name))
1309 repGensym (MkC lit_str) = rep2 newNameName [lit_str]
1310
1311 repBindQ :: Type -> Type        -- a and b
1312          -> Core (TH.Q a) -> Core (a -> TH.Q b) -> DsM (Core (TH.Q b))
1313 repBindQ ty_a ty_b (MkC x) (MkC y) 
1314   = rep2 bindQName [Type ty_a, Type ty_b, x, y] 
1315
1316 repSequenceQ :: Type -> Core [TH.Q a] -> DsM (Core (TH.Q [a]))
1317 repSequenceQ ty_a (MkC list)
1318   = rep2 sequenceQName [Type ty_a, list]
1319
1320 ------------ Lists and Tuples -------------------
1321 -- turn a list of patterns into a single pattern matching a list
1322
1323 coreList :: Name        -- Of the TyCon of the element type
1324          -> [Core a] -> DsM (Core [a])
1325 coreList tc_name es 
1326   = do { elt_ty <- lookupType tc_name; return (coreList' elt_ty es) }
1327
1328 coreList' :: Type       -- The element type
1329           -> [Core a] -> Core [a]
1330 coreList' elt_ty es = MkC (mkListExpr elt_ty (map unC es ))
1331
1332 nonEmptyCoreList :: [Core a] -> Core [a]
1333   -- The list must be non-empty so we can get the element type
1334   -- Otherwise use coreList
1335 nonEmptyCoreList []           = panic "coreList: empty argument"
1336 nonEmptyCoreList xs@(MkC x:_) = MkC (mkListExpr (exprType x) (map unC xs))
1337
1338 coreStringLit :: String -> DsM (Core String)
1339 coreStringLit s = do { z <- mkStringExpr s; return(MkC z) }
1340
1341 coreIntLit :: Int -> DsM (Core Int)
1342 coreIntLit i = return (MkC (mkIntExpr (fromIntegral i)))
1343
1344 coreVar :: Id -> Core TH.Name   -- The Id has type Name
1345 coreVar id = MkC (Var id)
1346
1347 ----------------- Failure -----------------------
1348 notHandled :: String -> SDoc -> DsM a
1349 notHandled what doc = failWithDs msg
1350   where
1351     msg = hang (text what <+> ptext (sLit "not (yet) handled by Template Haskell")) 
1352              2 doc
1353
1354
1355 -- %************************************************************************
1356 -- %*                                                                   *
1357 --              The known-key names for Template Haskell
1358 -- %*                                                                   *
1359 -- %************************************************************************
1360
1361 -- To add a name, do three things
1362 -- 
1363 --  1) Allocate a key
1364 --  2) Make a "Name"
1365 --  3) Add the name to knownKeyNames
1366
1367 templateHaskellNames :: [Name]
1368 -- The names that are implicitly mentioned by ``bracket''
1369 -- Should stay in sync with the import list of DsMeta
1370
1371 templateHaskellNames = [
1372     returnQName, bindQName, sequenceQName, newNameName, liftName,
1373     mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName, mkNameLName, 
1374
1375     -- Lit
1376     charLName, stringLName, integerLName, intPrimLName, wordPrimLName,
1377     floatPrimLName, doublePrimLName, rationalLName,
1378     -- Pat
1379     litPName, varPName, tupPName, conPName, tildePName, infixPName,
1380     asPName, wildPName, recPName, listPName, sigPName,
1381     -- FieldPat
1382     fieldPatName,
1383     -- Match
1384     matchName,
1385     -- Clause
1386     clauseName,
1387     -- Exp
1388     varEName, conEName, litEName, appEName, infixEName,
1389     infixAppName, sectionLName, sectionRName, lamEName, tupEName,
1390     condEName, letEName, caseEName, doEName, compEName,
1391     fromEName, fromThenEName, fromToEName, fromThenToEName,
1392     listEName, sigEName, recConEName, recUpdEName,
1393     -- FieldExp
1394     fieldExpName,
1395     -- Body
1396     guardedBName, normalBName,
1397     -- Guard
1398     normalGEName, patGEName,
1399     -- Stmt
1400     bindSName, letSName, noBindSName, parSName,
1401     -- Dec
1402     funDName, valDName, dataDName, newtypeDName, tySynDName,
1403     classDName, instanceDName, sigDName, forImpDName,
1404     -- Cxt
1405     cxtName,
1406     -- Strict
1407     isStrictName, notStrictName,
1408     -- Con
1409     normalCName, recCName, infixCName, forallCName,
1410     -- StrictType
1411     strictTypeName,
1412     -- VarStrictType
1413     varStrictTypeName,
1414     -- Type
1415     forallTName, varTName, conTName, appTName,
1416     tupleTName, arrowTName, listTName,
1417     -- Callconv
1418     cCallName, stdCallName,
1419     -- Safety
1420     unsafeName,
1421     safeName,
1422     threadsafeName,
1423     -- FunDep
1424     funDepName,
1425
1426     -- And the tycons
1427     qTyConName, nameTyConName, patTyConName, fieldPatTyConName, matchQTyConName,
1428     clauseQTyConName, expQTyConName, fieldExpTyConName, stmtQTyConName,
1429     decQTyConName, conQTyConName, strictTypeQTyConName,
1430     varStrictTypeQTyConName, typeQTyConName, expTyConName, decTyConName,
1431     typeTyConName, matchTyConName, clauseTyConName, patQTyConName,
1432     fieldPatQTyConName, fieldExpQTyConName, funDepTyConName,
1433
1434     -- Quasiquoting
1435     quoteExpName, quotePatName]
1436
1437 thSyn, thLib, qqLib :: Module
1438 thSyn = mkTHModule (fsLit "Language.Haskell.TH.Syntax")
1439 thLib = mkTHModule (fsLit "Language.Haskell.TH.Lib")
1440 qqLib = mkTHModule (fsLit "Language.Haskell.TH.Quote")
1441
1442 mkTHModule :: FastString -> Module
1443 mkTHModule m = mkModule thPackageId (mkModuleNameFS m)
1444
1445 libFun, libTc, thFun, thTc, qqFun :: FastString -> Unique -> Name
1446 libFun = mk_known_key_name OccName.varName thLib
1447 libTc  = mk_known_key_name OccName.tcName  thLib
1448 thFun  = mk_known_key_name OccName.varName thSyn
1449 thTc   = mk_known_key_name OccName.tcName  thSyn
1450 qqFun  = mk_known_key_name OccName.varName qqLib
1451
1452 -------------------- TH.Syntax -----------------------
1453 qTyConName, nameTyConName, fieldExpTyConName, patTyConName,
1454     fieldPatTyConName, expTyConName, decTyConName, typeTyConName,
1455     matchTyConName, clauseTyConName, funDepTyConName :: Name
1456 qTyConName        = thTc (fsLit "Q")            qTyConKey
1457 nameTyConName     = thTc (fsLit "Name")         nameTyConKey
1458 fieldExpTyConName = thTc (fsLit "FieldExp")     fieldExpTyConKey
1459 patTyConName      = thTc (fsLit "Pat")          patTyConKey
1460 fieldPatTyConName = thTc (fsLit "FieldPat")     fieldPatTyConKey
1461 expTyConName      = thTc (fsLit "Exp")          expTyConKey
1462 decTyConName      = thTc (fsLit "Dec")          decTyConKey
1463 typeTyConName     = thTc (fsLit "Type")         typeTyConKey
1464 matchTyConName    = thTc (fsLit "Match")        matchTyConKey
1465 clauseTyConName   = thTc (fsLit "Clause")       clauseTyConKey
1466 funDepTyConName   = thTc (fsLit "FunDep")       funDepTyConKey
1467
1468 returnQName, bindQName, sequenceQName, newNameName, liftName,
1469     mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName,
1470     mkNameLName :: Name
1471 returnQName   = thFun (fsLit "returnQ")   returnQIdKey
1472 bindQName     = thFun (fsLit "bindQ")     bindQIdKey
1473 sequenceQName = thFun (fsLit "sequenceQ") sequenceQIdKey
1474 newNameName    = thFun (fsLit "newName")   newNameIdKey
1475 liftName      = thFun (fsLit "lift")      liftIdKey
1476 mkNameName     = thFun (fsLit "mkName")     mkNameIdKey
1477 mkNameG_vName  = thFun (fsLit "mkNameG_v")  mkNameG_vIdKey
1478 mkNameG_dName  = thFun (fsLit "mkNameG_d")  mkNameG_dIdKey
1479 mkNameG_tcName = thFun (fsLit "mkNameG_tc") mkNameG_tcIdKey
1480 mkNameLName    = thFun (fsLit "mkNameL")    mkNameLIdKey
1481
1482
1483 -------------------- TH.Lib -----------------------
1484 -- data Lit = ...
1485 charLName, stringLName, integerLName, intPrimLName, wordPrimLName,
1486     floatPrimLName, doublePrimLName, rationalLName :: Name
1487 charLName       = libFun (fsLit "charL")       charLIdKey
1488 stringLName     = libFun (fsLit "stringL")     stringLIdKey
1489 integerLName    = libFun (fsLit "integerL")    integerLIdKey
1490 intPrimLName    = libFun (fsLit "intPrimL")    intPrimLIdKey
1491 wordPrimLName   = libFun (fsLit "wordPrimL")   wordPrimLIdKey
1492 floatPrimLName  = libFun (fsLit "floatPrimL")  floatPrimLIdKey
1493 doublePrimLName = libFun (fsLit "doublePrimL") doublePrimLIdKey
1494 rationalLName   = libFun (fsLit "rationalL")     rationalLIdKey
1495
1496 -- data Pat = ...
1497 litPName, varPName, tupPName, conPName, infixPName, tildePName,
1498     asPName, wildPName, recPName, listPName, sigPName :: Name
1499 litPName   = libFun (fsLit "litP")   litPIdKey
1500 varPName   = libFun (fsLit "varP")   varPIdKey
1501 tupPName   = libFun (fsLit "tupP")   tupPIdKey
1502 conPName   = libFun (fsLit "conP")   conPIdKey
1503 infixPName = libFun (fsLit "infixP") infixPIdKey
1504 tildePName = libFun (fsLit "tildeP") tildePIdKey
1505 asPName    = libFun (fsLit "asP")    asPIdKey
1506 wildPName  = libFun (fsLit "wildP")  wildPIdKey
1507 recPName   = libFun (fsLit "recP")   recPIdKey
1508 listPName  = libFun (fsLit "listP")  listPIdKey
1509 sigPName   = libFun (fsLit "sigP")   sigPIdKey
1510
1511 -- type FieldPat = ...
1512 fieldPatName :: Name
1513 fieldPatName = libFun (fsLit "fieldPat") fieldPatIdKey
1514
1515 -- data Match = ...
1516 matchName :: Name
1517 matchName = libFun (fsLit "match") matchIdKey
1518
1519 -- data Clause = ...
1520 clauseName :: Name
1521 clauseName = libFun (fsLit "clause") clauseIdKey
1522
1523 -- data Exp = ...
1524 varEName, conEName, litEName, appEName, infixEName, infixAppName,
1525     sectionLName, sectionRName, lamEName, tupEName, condEName,
1526     letEName, caseEName, doEName, compEName :: Name
1527 varEName        = libFun (fsLit "varE")        varEIdKey
1528 conEName        = libFun (fsLit "conE")        conEIdKey
1529 litEName        = libFun (fsLit "litE")        litEIdKey
1530 appEName        = libFun (fsLit "appE")        appEIdKey
1531 infixEName      = libFun (fsLit "infixE")      infixEIdKey
1532 infixAppName    = libFun (fsLit "infixApp")    infixAppIdKey
1533 sectionLName    = libFun (fsLit "sectionL")    sectionLIdKey
1534 sectionRName    = libFun (fsLit "sectionR")    sectionRIdKey
1535 lamEName        = libFun (fsLit "lamE")        lamEIdKey
1536 tupEName        = libFun (fsLit "tupE")        tupEIdKey
1537 condEName       = libFun (fsLit "condE")       condEIdKey
1538 letEName        = libFun (fsLit "letE")        letEIdKey
1539 caseEName       = libFun (fsLit "caseE")       caseEIdKey
1540 doEName         = libFun (fsLit "doE")         doEIdKey
1541 compEName       = libFun (fsLit "compE")       compEIdKey
1542 -- ArithSeq skips a level
1543 fromEName, fromThenEName, fromToEName, fromThenToEName :: Name
1544 fromEName       = libFun (fsLit "fromE")       fromEIdKey
1545 fromThenEName   = libFun (fsLit "fromThenE")   fromThenEIdKey
1546 fromToEName     = libFun (fsLit "fromToE")     fromToEIdKey
1547 fromThenToEName = libFun (fsLit "fromThenToE") fromThenToEIdKey
1548 -- end ArithSeq
1549 listEName, sigEName, recConEName, recUpdEName :: Name
1550 listEName       = libFun (fsLit "listE")       listEIdKey
1551 sigEName        = libFun (fsLit "sigE")        sigEIdKey
1552 recConEName     = libFun (fsLit "recConE")     recConEIdKey
1553 recUpdEName     = libFun (fsLit "recUpdE")     recUpdEIdKey
1554
1555 -- type FieldExp = ...
1556 fieldExpName :: Name
1557 fieldExpName = libFun (fsLit "fieldExp") fieldExpIdKey
1558
1559 -- data Body = ...
1560 guardedBName, normalBName :: Name
1561 guardedBName = libFun (fsLit "guardedB") guardedBIdKey
1562 normalBName  = libFun (fsLit "normalB")  normalBIdKey
1563
1564 -- data Guard = ...
1565 normalGEName, patGEName :: Name
1566 normalGEName = libFun (fsLit "normalGE") normalGEIdKey
1567 patGEName    = libFun (fsLit "patGE")    patGEIdKey
1568
1569 -- data Stmt = ...
1570 bindSName, letSName, noBindSName, parSName :: Name
1571 bindSName   = libFun (fsLit "bindS")   bindSIdKey
1572 letSName    = libFun (fsLit "letS")    letSIdKey
1573 noBindSName = libFun (fsLit "noBindS") noBindSIdKey
1574 parSName    = libFun (fsLit "parS")    parSIdKey
1575
1576 -- data Dec = ...
1577 funDName, valDName, dataDName, newtypeDName, tySynDName, classDName,
1578     instanceDName, sigDName, forImpDName :: Name
1579 funDName      = libFun (fsLit "funD")      funDIdKey
1580 valDName      = libFun (fsLit "valD")      valDIdKey
1581 dataDName     = libFun (fsLit "dataD")     dataDIdKey
1582 newtypeDName  = libFun (fsLit "newtypeD")  newtypeDIdKey
1583 tySynDName    = libFun (fsLit "tySynD")    tySynDIdKey
1584 classDName    = libFun (fsLit "classD")    classDIdKey
1585 instanceDName = libFun (fsLit "instanceD") instanceDIdKey
1586 sigDName      = libFun (fsLit "sigD")      sigDIdKey
1587 forImpDName   = libFun (fsLit "forImpD")   forImpDIdKey
1588
1589 -- type Ctxt = ...
1590 cxtName :: Name
1591 cxtName = libFun (fsLit "cxt") cxtIdKey
1592
1593 -- data Strict = ...
1594 isStrictName, notStrictName :: Name
1595 isStrictName      = libFun  (fsLit "isStrict")      isStrictKey
1596 notStrictName     = libFun  (fsLit "notStrict")     notStrictKey
1597
1598 -- data Con = ...
1599 normalCName, recCName, infixCName, forallCName :: Name
1600 normalCName = libFun (fsLit "normalC") normalCIdKey
1601 recCName    = libFun (fsLit "recC")    recCIdKey
1602 infixCName  = libFun (fsLit "infixC")  infixCIdKey
1603 forallCName  = libFun (fsLit "forallC")  forallCIdKey
1604
1605 -- type StrictType = ...
1606 strictTypeName :: Name
1607 strictTypeName    = libFun  (fsLit "strictType")    strictTKey
1608
1609 -- type VarStrictType = ...
1610 varStrictTypeName :: Name
1611 varStrictTypeName = libFun  (fsLit "varStrictType") varStrictTKey
1612
1613 -- data Type = ...
1614 forallTName, varTName, conTName, tupleTName, arrowTName,
1615     listTName, appTName :: Name
1616 forallTName = libFun (fsLit "forallT") forallTIdKey
1617 varTName    = libFun (fsLit "varT")    varTIdKey
1618 conTName    = libFun (fsLit "conT")    conTIdKey
1619 tupleTName  = libFun (fsLit "tupleT") tupleTIdKey
1620 arrowTName  = libFun (fsLit "arrowT") arrowTIdKey
1621 listTName   = libFun (fsLit "listT")  listTIdKey
1622 appTName    = libFun (fsLit "appT")    appTIdKey
1623
1624 -- data Callconv = ...
1625 cCallName, stdCallName :: Name
1626 cCallName = libFun (fsLit "cCall") cCallIdKey
1627 stdCallName = libFun (fsLit "stdCall") stdCallIdKey
1628
1629 -- data Safety = ...
1630 unsafeName, safeName, threadsafeName :: Name
1631 unsafeName     = libFun (fsLit "unsafe") unsafeIdKey
1632 safeName       = libFun (fsLit "safe") safeIdKey
1633 threadsafeName = libFun (fsLit "threadsafe") threadsafeIdKey
1634
1635 -- data FunDep = ...
1636 funDepName :: Name
1637 funDepName     = libFun (fsLit "funDep") funDepIdKey
1638
1639 matchQTyConName, clauseQTyConName, expQTyConName, stmtQTyConName,
1640     decQTyConName, conQTyConName, strictTypeQTyConName,
1641     varStrictTypeQTyConName, typeQTyConName, fieldExpQTyConName,
1642     patQTyConName, fieldPatQTyConName :: Name
1643 matchQTyConName         = libTc (fsLit "MatchQ")        matchQTyConKey
1644 clauseQTyConName        = libTc (fsLit "ClauseQ")       clauseQTyConKey
1645 expQTyConName           = libTc (fsLit "ExpQ")          expQTyConKey
1646 stmtQTyConName          = libTc (fsLit "StmtQ")         stmtQTyConKey
1647 decQTyConName           = libTc (fsLit "DecQ")          decQTyConKey
1648 conQTyConName           = libTc (fsLit "ConQ")          conQTyConKey
1649 strictTypeQTyConName    = libTc (fsLit "StrictTypeQ")    strictTypeQTyConKey
1650 varStrictTypeQTyConName = libTc (fsLit "VarStrictTypeQ") varStrictTypeQTyConKey
1651 typeQTyConName          = libTc (fsLit "TypeQ")          typeQTyConKey
1652 fieldExpQTyConName      = libTc (fsLit "FieldExpQ")      fieldExpQTyConKey
1653 patQTyConName           = libTc (fsLit "PatQ")           patQTyConKey
1654 fieldPatQTyConName      = libTc (fsLit "FieldPatQ")      fieldPatQTyConKey
1655
1656 -- quasiquoting
1657 quoteExpName, quotePatName :: Name
1658 quoteExpName        = qqFun (fsLit "quoteExp") quoteExpKey
1659 quotePatName        = qqFun (fsLit "quotePat") quotePatKey
1660
1661 -- TyConUniques available: 100-129
1662 -- Check in PrelNames if you want to change this
1663
1664 expTyConKey, matchTyConKey, clauseTyConKey, qTyConKey, expQTyConKey,
1665     decQTyConKey, patTyConKey, matchQTyConKey, clauseQTyConKey,
1666     stmtQTyConKey, conQTyConKey, typeQTyConKey, typeTyConKey,
1667     decTyConKey, varStrictTypeQTyConKey, strictTypeQTyConKey,
1668     fieldExpTyConKey, fieldPatTyConKey, nameTyConKey, patQTyConKey,
1669     fieldPatQTyConKey, fieldExpQTyConKey, funDepTyConKey :: Unique
1670 expTyConKey             = mkPreludeTyConUnique 100
1671 matchTyConKey           = mkPreludeTyConUnique 101
1672 clauseTyConKey          = mkPreludeTyConUnique 102
1673 qTyConKey               = mkPreludeTyConUnique 103
1674 expQTyConKey            = mkPreludeTyConUnique 104
1675 decQTyConKey            = mkPreludeTyConUnique 105
1676 patTyConKey             = mkPreludeTyConUnique 106
1677 matchQTyConKey          = mkPreludeTyConUnique 107
1678 clauseQTyConKey         = mkPreludeTyConUnique 108
1679 stmtQTyConKey           = mkPreludeTyConUnique 109
1680 conQTyConKey            = mkPreludeTyConUnique 110
1681 typeQTyConKey           = mkPreludeTyConUnique 111
1682 typeTyConKey            = mkPreludeTyConUnique 112
1683 decTyConKey             = mkPreludeTyConUnique 113
1684 varStrictTypeQTyConKey  = mkPreludeTyConUnique 114
1685 strictTypeQTyConKey     = mkPreludeTyConUnique 115
1686 fieldExpTyConKey        = mkPreludeTyConUnique 116
1687 fieldPatTyConKey        = mkPreludeTyConUnique 117
1688 nameTyConKey            = mkPreludeTyConUnique 118
1689 patQTyConKey            = mkPreludeTyConUnique 119
1690 fieldPatQTyConKey       = mkPreludeTyConUnique 120
1691 fieldExpQTyConKey       = mkPreludeTyConUnique 121
1692 funDepTyConKey          = mkPreludeTyConUnique 122
1693
1694 -- IdUniques available: 200-399
1695 -- If you want to change this, make sure you check in PrelNames
1696
1697 returnQIdKey, bindQIdKey, sequenceQIdKey, liftIdKey, newNameIdKey,
1698     mkNameIdKey, mkNameG_vIdKey, mkNameG_dIdKey, mkNameG_tcIdKey,
1699     mkNameLIdKey :: Unique
1700 returnQIdKey        = mkPreludeMiscIdUnique 200
1701 bindQIdKey          = mkPreludeMiscIdUnique 201
1702 sequenceQIdKey      = mkPreludeMiscIdUnique 202
1703 liftIdKey           = mkPreludeMiscIdUnique 203
1704 newNameIdKey         = mkPreludeMiscIdUnique 204
1705 mkNameIdKey          = mkPreludeMiscIdUnique 205
1706 mkNameG_vIdKey       = mkPreludeMiscIdUnique 206
1707 mkNameG_dIdKey       = mkPreludeMiscIdUnique 207
1708 mkNameG_tcIdKey      = mkPreludeMiscIdUnique 208
1709 mkNameLIdKey         = mkPreludeMiscIdUnique 209
1710
1711
1712 -- data Lit = ...
1713 charLIdKey, stringLIdKey, integerLIdKey, intPrimLIdKey, wordPrimLIdKey,
1714     floatPrimLIdKey, doublePrimLIdKey, rationalLIdKey :: Unique
1715 charLIdKey        = mkPreludeMiscIdUnique 210
1716 stringLIdKey      = mkPreludeMiscIdUnique 211
1717 integerLIdKey     = mkPreludeMiscIdUnique 212
1718 intPrimLIdKey     = mkPreludeMiscIdUnique 213
1719 wordPrimLIdKey    = mkPreludeMiscIdUnique 214
1720 floatPrimLIdKey   = mkPreludeMiscIdUnique 215
1721 doublePrimLIdKey  = mkPreludeMiscIdUnique 216
1722 rationalLIdKey    = mkPreludeMiscIdUnique 217
1723
1724 -- data Pat = ...
1725 litPIdKey, varPIdKey, tupPIdKey, conPIdKey, infixPIdKey, tildePIdKey,
1726     asPIdKey, wildPIdKey, recPIdKey, listPIdKey, sigPIdKey :: Unique
1727 litPIdKey         = mkPreludeMiscIdUnique 220
1728 varPIdKey         = mkPreludeMiscIdUnique 221
1729 tupPIdKey         = mkPreludeMiscIdUnique 222
1730 conPIdKey         = mkPreludeMiscIdUnique 223
1731 infixPIdKey       = mkPreludeMiscIdUnique 312
1732 tildePIdKey       = mkPreludeMiscIdUnique 224
1733 asPIdKey          = mkPreludeMiscIdUnique 225
1734 wildPIdKey        = mkPreludeMiscIdUnique 226
1735 recPIdKey         = mkPreludeMiscIdUnique 227
1736 listPIdKey        = mkPreludeMiscIdUnique 228
1737 sigPIdKey         = mkPreludeMiscIdUnique 229
1738
1739 -- type FieldPat = ...
1740 fieldPatIdKey :: Unique
1741 fieldPatIdKey       = mkPreludeMiscIdUnique 230
1742
1743 -- data Match = ...
1744 matchIdKey :: Unique
1745 matchIdKey          = mkPreludeMiscIdUnique 231
1746
1747 -- data Clause = ...
1748 clauseIdKey :: Unique
1749 clauseIdKey         = mkPreludeMiscIdUnique 232
1750
1751 -- data Exp = ...
1752 varEIdKey, conEIdKey, litEIdKey, appEIdKey, infixEIdKey, infixAppIdKey,
1753     sectionLIdKey, sectionRIdKey, lamEIdKey, tupEIdKey, condEIdKey,
1754     letEIdKey, caseEIdKey, doEIdKey, compEIdKey,
1755     fromEIdKey, fromThenEIdKey, fromToEIdKey, fromThenToEIdKey,
1756     listEIdKey, sigEIdKey, recConEIdKey, recUpdEIdKey :: Unique
1757 varEIdKey         = mkPreludeMiscIdUnique 240
1758 conEIdKey         = mkPreludeMiscIdUnique 241
1759 litEIdKey         = mkPreludeMiscIdUnique 242
1760 appEIdKey         = mkPreludeMiscIdUnique 243
1761 infixEIdKey       = mkPreludeMiscIdUnique 244
1762 infixAppIdKey       = mkPreludeMiscIdUnique 245
1763 sectionLIdKey       = mkPreludeMiscIdUnique 246
1764 sectionRIdKey       = mkPreludeMiscIdUnique 247
1765 lamEIdKey         = mkPreludeMiscIdUnique 248
1766 tupEIdKey         = mkPreludeMiscIdUnique 249
1767 condEIdKey        = mkPreludeMiscIdUnique 250
1768 letEIdKey         = mkPreludeMiscIdUnique 251
1769 caseEIdKey        = mkPreludeMiscIdUnique 252
1770 doEIdKey          = mkPreludeMiscIdUnique 253
1771 compEIdKey        = mkPreludeMiscIdUnique 254
1772 fromEIdKey        = mkPreludeMiscIdUnique 255
1773 fromThenEIdKey    = mkPreludeMiscIdUnique 256
1774 fromToEIdKey      = mkPreludeMiscIdUnique 257
1775 fromThenToEIdKey  = mkPreludeMiscIdUnique 258
1776 listEIdKey        = mkPreludeMiscIdUnique 259
1777 sigEIdKey         = mkPreludeMiscIdUnique 260
1778 recConEIdKey      = mkPreludeMiscIdUnique 261
1779 recUpdEIdKey      = mkPreludeMiscIdUnique 262
1780
1781 -- type FieldExp = ...
1782 fieldExpIdKey :: Unique
1783 fieldExpIdKey       = mkPreludeMiscIdUnique 265
1784
1785 -- data Body = ...
1786 guardedBIdKey, normalBIdKey :: Unique
1787 guardedBIdKey     = mkPreludeMiscIdUnique 266
1788 normalBIdKey      = mkPreludeMiscIdUnique 267
1789
1790 -- data Guard = ...
1791 normalGEIdKey, patGEIdKey :: Unique
1792 normalGEIdKey     = mkPreludeMiscIdUnique 310
1793 patGEIdKey        = mkPreludeMiscIdUnique 311
1794
1795 -- data Stmt = ...
1796 bindSIdKey, letSIdKey, noBindSIdKey, parSIdKey :: Unique
1797 bindSIdKey       = mkPreludeMiscIdUnique 268
1798 letSIdKey        = mkPreludeMiscIdUnique 269
1799 noBindSIdKey     = mkPreludeMiscIdUnique 270
1800 parSIdKey        = mkPreludeMiscIdUnique 271
1801
1802 -- data Dec = ...
1803 funDIdKey, valDIdKey, dataDIdKey, newtypeDIdKey, tySynDIdKey,
1804     classDIdKey, instanceDIdKey, sigDIdKey, forImpDIdKey :: Unique
1805 funDIdKey         = mkPreludeMiscIdUnique 272
1806 valDIdKey         = mkPreludeMiscIdUnique 273
1807 dataDIdKey        = mkPreludeMiscIdUnique 274
1808 newtypeDIdKey     = mkPreludeMiscIdUnique 275
1809 tySynDIdKey       = mkPreludeMiscIdUnique 276
1810 classDIdKey       = mkPreludeMiscIdUnique 277
1811 instanceDIdKey    = mkPreludeMiscIdUnique 278
1812 sigDIdKey         = mkPreludeMiscIdUnique 279
1813 forImpDIdKey      = mkPreludeMiscIdUnique 297
1814
1815 -- type Cxt = ...
1816 cxtIdKey :: Unique
1817 cxtIdKey            = mkPreludeMiscIdUnique 280
1818
1819 -- data Strict = ...
1820 isStrictKey, notStrictKey :: Unique
1821 isStrictKey         = mkPreludeMiscIdUnique 281
1822 notStrictKey        = mkPreludeMiscIdUnique 282
1823
1824 -- data Con = ...
1825 normalCIdKey, recCIdKey, infixCIdKey, forallCIdKey :: Unique
1826 normalCIdKey      = mkPreludeMiscIdUnique 283
1827 recCIdKey         = mkPreludeMiscIdUnique 284
1828 infixCIdKey       = mkPreludeMiscIdUnique 285
1829 forallCIdKey      = mkPreludeMiscIdUnique 288
1830
1831 -- type StrictType = ...
1832 strictTKey :: Unique
1833 strictTKey        = mkPreludeMiscIdUnique 286
1834
1835 -- type VarStrictType = ...
1836 varStrictTKey :: Unique
1837 varStrictTKey     = mkPreludeMiscIdUnique 287
1838
1839 -- data Type = ...
1840 forallTIdKey, varTIdKey, conTIdKey, tupleTIdKey, arrowTIdKey,
1841     listTIdKey, appTIdKey :: Unique
1842 forallTIdKey      = mkPreludeMiscIdUnique 290
1843 varTIdKey         = mkPreludeMiscIdUnique 291
1844 conTIdKey         = mkPreludeMiscIdUnique 292
1845 tupleTIdKey       = mkPreludeMiscIdUnique 294
1846 arrowTIdKey       = mkPreludeMiscIdUnique 295
1847 listTIdKey        = mkPreludeMiscIdUnique 296
1848 appTIdKey         = mkPreludeMiscIdUnique 293
1849
1850 -- data Callconv = ...
1851 cCallIdKey, stdCallIdKey :: Unique
1852 cCallIdKey      = mkPreludeMiscIdUnique 300
1853 stdCallIdKey    = mkPreludeMiscIdUnique 301
1854
1855 -- data Safety = ...
1856 unsafeIdKey, safeIdKey, threadsafeIdKey :: Unique
1857 unsafeIdKey     = mkPreludeMiscIdUnique 305
1858 safeIdKey       = mkPreludeMiscIdUnique 306
1859 threadsafeIdKey = mkPreludeMiscIdUnique 307
1860
1861 -- data FunDep = ...
1862 funDepIdKey :: Unique
1863 funDepIdKey = mkPreludeMiscIdUnique 320
1864
1865 -- quasiquoting
1866 quoteExpKey, quotePatKey :: Unique
1867 quoteExpKey = mkPreludeMiscIdUnique 321
1868 quotePatKey = mkPreludeMiscIdUnique 322
1869