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