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