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