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