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