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