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