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