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