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