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