Remove platform CPP from nativeGen/PPC/CodeGen.hs
[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 []    = return ([],[])
884 repSts other = notHandled "Exotic statement" (ppr other)
885
886
887 -----------------------------------------------------------
888 --                      Bindings
889 -----------------------------------------------------------
890
891 repBinds :: HsLocalBinds Name -> DsM ([GenSymBind], Core [TH.DecQ]) 
892 repBinds EmptyLocalBinds
893   = do  { core_list <- coreList decQTyConName []
894         ; return ([], core_list) }
895
896 repBinds b@(HsIPBinds _) = notHandled "Implicit parameters" (ppr b)
897
898 repBinds (HsValBinds decs)
899  = do   { let { bndrs = collectHsValBinders decs }
900                 -- No need to worrry about detailed scopes within
901                 -- the binding group, because we are talking Names
902                 -- here, so we can safely treat it as a mutually 
903                 -- recursive group
904         ; ss        <- mkGenSyms bndrs
905         ; prs       <- addBinds ss (rep_val_binds decs)
906         ; core_list <- coreList decQTyConName 
907                                 (de_loc (sort_by_loc prs))
908         ; return (ss, core_list) }
909
910 rep_val_binds :: HsValBinds Name -> DsM [(SrcSpan, Core TH.DecQ)]
911 -- Assumes: all the binders of the binding are alrady in the meta-env
912 rep_val_binds (ValBindsOut binds sigs)
913  = do { core1 <- rep_binds' (unionManyBags (map snd binds))
914       ; core2 <- rep_sigs' sigs
915       ; return (core1 ++ core2) }
916 rep_val_binds (ValBindsIn _ _)
917  = panic "rep_val_binds: ValBindsIn"
918
919 rep_binds :: LHsBinds Name -> DsM [Core TH.DecQ]
920 rep_binds binds = do { binds_w_locs <- rep_binds' binds
921                      ; return (de_loc (sort_by_loc binds_w_locs)) }
922
923 rep_binds' :: LHsBinds Name -> DsM [(SrcSpan, Core TH.DecQ)]
924 rep_binds' binds = mapM rep_bind (bagToList binds)
925
926 rep_bind :: LHsBind Name -> DsM (SrcSpan, Core TH.DecQ)
927 -- Assumes: all the binders of the binding are alrady in the meta-env
928
929 -- Note GHC treats declarations of a variable (not a pattern) 
930 -- e.g.  x = g 5 as a Fun MonoBinds. This is indicated by a single match 
931 -- with an empty list of patterns
932 rep_bind (L loc (FunBind { fun_id = fn, 
933                            fun_matches = MatchGroup [L _ (Match [] _ (GRHSs guards wheres))] _ }))
934  = do { (ss,wherecore) <- repBinds wheres
935         ; guardcore <- addBinds ss (repGuards guards)
936         ; fn'  <- lookupLBinder fn
937         ; p    <- repPvar fn'
938         ; ans  <- repVal p guardcore wherecore
939         ; ans' <- wrapGenSyms ss ans
940         ; return (loc, ans') }
941
942 rep_bind (L loc (FunBind { fun_id = fn, fun_matches = MatchGroup ms _ }))
943  =   do { ms1 <- mapM repClauseTup ms
944         ; fn' <- lookupLBinder fn
945         ; ans <- repFun fn' (nonEmptyCoreList ms1)
946         ; return (loc, ans) }
947
948 rep_bind (L loc (PatBind { pat_lhs = pat, pat_rhs = GRHSs guards wheres }))
949  =   do { patcore <- repLP pat 
950         ; (ss,wherecore) <- repBinds wheres
951         ; guardcore <- addBinds ss (repGuards guards)
952         ; ans  <- repVal patcore guardcore wherecore
953         ; ans' <- wrapGenSyms ss ans
954         ; return (loc, ans') }
955
956 rep_bind (L _ (VarBind { var_id = v, var_rhs = e}))
957  =   do { v' <- lookupBinder v 
958         ; e2 <- repLE e
959         ; x <- repNormal e2
960         ; patcore <- repPvar v'
961         ; empty_decls <- coreList decQTyConName [] 
962         ; ans <- repVal patcore x empty_decls
963         ; return (srcLocSpan (getSrcLoc v), ans) }
964
965 rep_bind (L _ (AbsBinds {}))  = panic "rep_bind: AbsBinds"
966
967 -----------------------------------------------------------------------------
968 -- Since everything in a Bind is mutually recursive we need rename all
969 -- all the variables simultaneously. For example: 
970 -- [| AndMonoBinds (f x = x + g 2) (g x = f 1 + 2) |] would translate to
971 -- do { f'1 <- gensym "f"
972 --    ; g'2 <- gensym "g"
973 --    ; [ do { x'3 <- gensym "x"; fun f'1 [pvar x'3] [| x + g2 |]},
974 --        do { x'4 <- gensym "x"; fun g'2 [pvar x'4] [| f 1 + 2 |]}
975 --      ]}
976 -- This requires collecting the bindings (f'1 <- gensym "f"), and the 
977 -- environment ( f |-> f'1 ) from each binding, and then unioning them 
978 -- together. As we do this we collect GenSymBinds's which represent the renamed 
979 -- variables bound by the Bindings. In order not to lose track of these 
980 -- representations we build a shadow datatype MB with the same structure as 
981 -- MonoBinds, but which has slots for the representations
982
983
984 -----------------------------------------------------------------------------
985 -- GHC allows a more general form of lambda abstraction than specified
986 -- by Haskell 98. In particular it allows guarded lambda's like : 
987 -- (\  x | even x -> 0 | odd x -> 1) at the moment we can't represent this in
988 -- Haskell Template's Meta.Exp type so we punt if it isn't a simple thing like
989 -- (\ p1 .. pn -> exp) by causing an error.  
990
991 repLambda :: LMatch Name -> DsM (Core TH.ExpQ)
992 repLambda (L _ (Match ps _ (GRHSs [L _ (GRHS [] e)] EmptyLocalBinds)))
993  = do { let bndrs = collectPatsBinders ps ;
994       ; ss  <- mkGenSyms bndrs
995       ; lam <- addBinds ss (
996                 do { xs <- repLPs ps; body <- repLE e; repLam xs body })
997       ; wrapGenSyms ss lam }
998
999 repLambda (L _ m) = notHandled "Guarded labmdas" (pprMatch (LambdaExpr :: HsMatchContext Name) m)
1000
1001   
1002 -----------------------------------------------------------------------------
1003 --                      Patterns
1004 -- repP deals with patterns.  It assumes that we have already
1005 -- walked over the pattern(s) once to collect the binders, and 
1006 -- have extended the environment.  So every pattern-bound 
1007 -- variable should already appear in the environment.
1008
1009 -- Process a list of patterns
1010 repLPs :: [LPat Name] -> DsM (Core [TH.PatQ])
1011 repLPs ps = do { ps' <- mapM repLP ps ;
1012                  coreList patQTyConName ps' }
1013
1014 repLP :: LPat Name -> DsM (Core TH.PatQ)
1015 repLP (L _ p) = repP p
1016
1017 repP :: Pat Name -> DsM (Core TH.PatQ)
1018 repP (WildPat _)       = repPwild 
1019 repP (LitPat l)        = do { l2 <- repLiteral l; repPlit l2 }
1020 repP (VarPat x)        = do { x' <- lookupBinder x; repPvar x' }
1021 repP (LazyPat p)       = do { p1 <- repLP p; repPtilde p1 }
1022 repP (BangPat p)       = do { p1 <- repLP p; repPbang p1 }
1023 repP (AsPat x p)       = do { x' <- lookupLBinder x; p1 <- repLP p; repPaspat x' p1 }
1024 repP (ParPat p)        = repLP p 
1025 repP (ListPat ps _)    = do { qs <- repLPs ps; repPlist qs }
1026 repP (TuplePat ps boxed _)
1027   | isBoxed boxed       = do { qs <- repLPs ps; repPtup qs }
1028   | otherwise           = do { qs <- repLPs ps; repPunboxedTup qs }
1029 repP (ConPatIn dc details)
1030  = do { con_str <- lookupLOcc dc
1031       ; case details of
1032          PrefixCon ps -> do { qs <- repLPs ps; repPcon con_str qs }
1033          RecCon rec   -> do { let flds = rec_flds rec
1034                             ; vs <- sequence $ map lookupLOcc (map hsRecFieldId flds)
1035                             ; ps <- sequence $ map repLP (map hsRecFieldArg flds)
1036                             ; fps <- zipWithM (\x y -> rep2 fieldPatName [unC x,unC y]) vs ps
1037                             ; fps' <- coreList fieldPatQTyConName fps
1038                             ; repPrec con_str fps' }
1039          InfixCon p1 p2 -> do { p1' <- repLP p1;
1040                                 p2' <- repLP p2;
1041                                 repPinfix p1' con_str p2' }
1042    }
1043 repP (NPat l Nothing _)  = do { a <- repOverloadedLiteral l; repPlit a }
1044 repP (ViewPat e p _) = do { e' <- repLE e; p' <- repLP p; repPview e' p' }
1045 repP p@(NPat _ (Just _) _) = notHandled "Negative overloaded patterns" (ppr p)
1046 repP p@(SigPatIn {})  = notHandled "Type signatures in patterns" (ppr p)
1047         -- The problem is to do with scoped type variables.
1048         -- To implement them, we have to implement the scoping rules
1049         -- here in DsMeta, and I don't want to do that today!
1050         --       do { p' <- repLP p; t' <- repLTy t; repPsig p' t' }
1051         --      repPsig :: Core TH.PatQ -> Core TH.TypeQ -> DsM (Core TH.PatQ)
1052         --      repPsig (MkC p) (MkC t) = rep2 sigPName [p, t]
1053
1054 repP other = notHandled "Exotic pattern" (ppr other)
1055
1056 ----------------------------------------------------------
1057 -- Declaration ordering helpers
1058
1059 sort_by_loc :: [(SrcSpan, a)] -> [(SrcSpan, a)]
1060 sort_by_loc xs = sortBy comp xs
1061     where comp x y = compare (fst x) (fst y)
1062
1063 de_loc :: [(a, b)] -> [b]
1064 de_loc = map snd
1065
1066 ----------------------------------------------------------
1067 --      The meta-environment
1068
1069 -- A name/identifier association for fresh names of locally bound entities
1070 type GenSymBind = (Name, Id)    -- Gensym the string and bind it to the Id
1071                                 -- I.e.         (x, x_id) means
1072                                 --      let x_id = gensym "x" in ...
1073
1074 -- Generate a fresh name for a locally bound entity
1075
1076 mkGenSyms :: [Name] -> DsM [GenSymBind]
1077 -- We can use the existing name.  For example:
1078 --      [| \x_77 -> x_77 + x_77 |]
1079 -- desugars to
1080 --      do { x_77 <- genSym "x"; .... }
1081 -- We use the same x_77 in the desugared program, but with the type Bndr
1082 -- instead of Int
1083 --
1084 -- We do make it an Internal name, though (hence localiseName)
1085 --
1086 -- Nevertheless, it's monadic because we have to generate nameTy
1087 mkGenSyms ns = do { var_ty <- lookupType nameTyConName
1088                   ; return [(nm, mkLocalId (localiseName nm) var_ty) | nm <- ns] }
1089
1090              
1091 addBinds :: [GenSymBind] -> DsM a -> DsM a
1092 -- Add a list of fresh names for locally bound entities to the 
1093 -- meta environment (which is part of the state carried around 
1094 -- by the desugarer monad) 
1095 addBinds bs m = dsExtendMetaEnv (mkNameEnv [(n,Bound id) | (n,id) <- bs]) m
1096
1097 -- Look up a locally bound name
1098 --
1099 lookupLBinder :: Located Name -> DsM (Core TH.Name)
1100 lookupLBinder (L _ n) = lookupBinder n
1101
1102 lookupBinder :: Name -> DsM (Core TH.Name)
1103 lookupBinder n 
1104   = do { mb_val <- dsLookupMetaEnv n;
1105          case mb_val of
1106             Just (Bound x) -> return (coreVar x)
1107             _              -> failWithDs msg }
1108   where
1109     msg = ptext (sLit "DsMeta: failed binder lookup when desugaring a TH bracket:") <+> ppr n
1110
1111 -- Look up a name that is either locally bound or a global name
1112 --
1113 --  * If it is a global name, generate the "original name" representation (ie,
1114 --   the <module>:<name> form) for the associated entity
1115 --
1116 lookupLOcc :: Located Name -> DsM (Core TH.Name)
1117 -- Lookup an occurrence; it can't be a splice.
1118 -- Use the in-scope bindings if they exist
1119 lookupLOcc (L _ n) = lookupOcc n
1120
1121 lookupOcc :: Name -> DsM (Core TH.Name)
1122 lookupOcc n
1123   = do {  mb_val <- dsLookupMetaEnv n ;
1124           case mb_val of
1125                 Nothing         -> globalVar n
1126                 Just (Bound x)  -> return (coreVar x)
1127                 Just (Splice _) -> pprPanic "repE:lookupOcc" (ppr n) 
1128     }
1129
1130 lookupTvOcc :: Name -> DsM (Core TH.Name)
1131 -- Type variables can't be staged and are not lexically scoped in TH
1132 lookupTvOcc n   
1133   = do {  mb_val <- dsLookupMetaEnv n ;
1134           case mb_val of
1135                 Just (Bound x)  -> return (coreVar x)
1136                 _               -> failWithDs msg
1137     }
1138   where
1139     msg = vcat  [ ptext (sLit "Illegal lexically-scoped type variable") <+> quotes (ppr n)
1140                 , ptext (sLit "Lexically scoped type variables are not supported by Template Haskell") ]
1141
1142 globalVar :: Name -> DsM (Core TH.Name)
1143 -- Not bound by the meta-env
1144 -- Could be top-level; or could be local
1145 --      f x = $(g [| x |])
1146 -- Here the x will be local
1147 globalVar name
1148   | isExternalName name
1149   = do  { MkC mod <- coreStringLit name_mod
1150         ; MkC pkg <- coreStringLit name_pkg
1151         ; MkC occ <- occNameLit name
1152         ; rep2 mk_varg [pkg,mod,occ] }
1153   | otherwise
1154   = do  { MkC occ <- occNameLit name
1155         ; MkC uni <- coreIntLit (getKey (getUnique name))
1156         ; rep2 mkNameLName [occ,uni] }
1157   where
1158       mod = ASSERT( isExternalName name) nameModule name
1159       name_mod = moduleNameString (moduleName mod)
1160       name_pkg = packageIdString (modulePackageId mod)
1161       name_occ = nameOccName name
1162       mk_varg | OccName.isDataOcc name_occ = mkNameG_dName
1163               | OccName.isVarOcc  name_occ = mkNameG_vName
1164               | OccName.isTcOcc   name_occ = mkNameG_tcName
1165               | otherwise                  = pprPanic "DsMeta.globalVar" (ppr name)
1166
1167 lookupType :: Name      -- Name of type constructor (e.g. TH.ExpQ)
1168            -> DsM Type  -- The type
1169 lookupType tc_name = do { tc <- dsLookupTyCon tc_name ;
1170                           return (mkTyConApp tc []) }
1171
1172 wrapGenSyms :: [GenSymBind] 
1173             -> Core (TH.Q a) -> DsM (Core (TH.Q a))
1174 -- wrapGenSyms [(nm1,id1), (nm2,id2)] y 
1175 --      --> bindQ (gensym nm1) (\ id1 -> 
1176 --          bindQ (gensym nm2 (\ id2 -> 
1177 --          y))
1178
1179 wrapGenSyms binds body@(MkC b)
1180   = do  { var_ty <- lookupType nameTyConName
1181         ; go var_ty binds }
1182   where
1183     [elt_ty] = tcTyConAppArgs (exprType b) 
1184         -- b :: Q a, so we can get the type 'a' by looking at the
1185         -- argument type. NB: this relies on Q being a data/newtype,
1186         -- not a type synonym
1187
1188     go _ [] = return body
1189     go var_ty ((name,id) : binds)
1190       = do { MkC body'  <- go var_ty binds
1191            ; lit_str    <- occNameLit name
1192            ; gensym_app <- repGensym lit_str
1193            ; repBindQ var_ty elt_ty 
1194                       gensym_app (MkC (Lam id body')) }
1195
1196 -- Just like wrapGenSym, but don't actually do the gensym
1197 -- Instead use the existing name:
1198 --      let x = "x" in ...
1199 -- Only used for [Decl], and for the class ops in class 
1200 -- and instance decls
1201 wrapNongenSyms :: [GenSymBind] -> Core a -> DsM (Core a)
1202 wrapNongenSyms binds (MkC body)
1203   = do { binds' <- mapM do_one binds ;
1204          return (MkC (mkLets binds' body)) }
1205   where
1206     do_one (name,id) 
1207         = do { MkC lit_str <- occNameLit name
1208              ; MkC var <- rep2 mkNameName [lit_str]
1209              ; return (NonRec id var) }
1210
1211 occNameLit :: Name -> DsM (Core String)
1212 occNameLit n = coreStringLit (occNameString (nameOccName n))
1213
1214
1215 -- %*********************************************************************
1216 -- %*                                                                   *
1217 --              Constructing code
1218 -- %*                                                                   *
1219 -- %*********************************************************************
1220
1221 -----------------------------------------------------------------------------
1222 -- PHANTOM TYPES for consistency. In order to make sure we do this correct 
1223 -- we invent a new datatype which uses phantom types.
1224
1225 newtype Core a = MkC CoreExpr
1226 unC :: Core a -> CoreExpr
1227 unC (MkC x) = x
1228
1229 rep2 :: Name -> [ CoreExpr ] -> DsM (Core a)
1230 rep2 n xs = do { id <- dsLookupGlobalId n
1231                ; return (MkC (foldl App (Var id) xs)) }
1232
1233 -- Then we make "repConstructors" which use the phantom types for each of the
1234 -- smart constructors of the Meta.Meta datatypes.
1235
1236
1237 -- %*********************************************************************
1238 -- %*                                                                   *
1239 --              The 'smart constructors'
1240 -- %*                                                                   *
1241 -- %*********************************************************************
1242
1243 --------------- Patterns -----------------
1244 repPlit   :: Core TH.Lit -> DsM (Core TH.PatQ) 
1245 repPlit (MkC l) = rep2 litPName [l]
1246
1247 repPvar :: Core TH.Name -> DsM (Core TH.PatQ)
1248 repPvar (MkC s) = rep2 varPName [s]
1249
1250 repPtup :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
1251 repPtup (MkC ps) = rep2 tupPName [ps]
1252
1253 repPunboxedTup :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
1254 repPunboxedTup (MkC ps) = rep2 unboxedTupPName [ps]
1255
1256 repPcon   :: Core TH.Name -> Core [TH.PatQ] -> DsM (Core TH.PatQ)
1257 repPcon (MkC s) (MkC ps) = rep2 conPName [s, ps]
1258
1259 repPrec   :: Core TH.Name -> Core [(TH.Name,TH.PatQ)] -> DsM (Core TH.PatQ)
1260 repPrec (MkC c) (MkC rps) = rep2 recPName [c,rps]
1261
1262 repPinfix :: Core TH.PatQ -> Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ)
1263 repPinfix (MkC p1) (MkC n) (MkC p2) = rep2 infixPName [p1, n, p2]
1264
1265 repPtilde :: Core TH.PatQ -> DsM (Core TH.PatQ)
1266 repPtilde (MkC p) = rep2 tildePName [p]
1267
1268 repPbang :: Core TH.PatQ -> DsM (Core TH.PatQ)
1269 repPbang (MkC p) = rep2 bangPName [p]
1270
1271 repPaspat :: Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ)
1272 repPaspat (MkC s) (MkC p) = rep2 asPName [s, p]
1273
1274 repPwild  :: DsM (Core TH.PatQ)
1275 repPwild = rep2 wildPName []
1276
1277 repPlist :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
1278 repPlist (MkC ps) = rep2 listPName [ps]
1279
1280 repPview :: Core TH.ExpQ -> Core TH.PatQ -> DsM (Core TH.PatQ)
1281 repPview (MkC e) (MkC p) = rep2 viewPName [e,p]
1282
1283 --------------- Expressions -----------------
1284 repVarOrCon :: Name -> Core TH.Name -> DsM (Core TH.ExpQ)
1285 repVarOrCon vc str | isDataOcc (nameOccName vc) = repCon str
1286                    | otherwise                  = repVar str
1287
1288 repVar :: Core TH.Name -> DsM (Core TH.ExpQ)
1289 repVar (MkC s) = rep2 varEName [s] 
1290
1291 repCon :: Core TH.Name -> DsM (Core TH.ExpQ)
1292 repCon (MkC s) = rep2 conEName [s] 
1293
1294 repLit :: Core TH.Lit -> DsM (Core TH.ExpQ)
1295 repLit (MkC c) = rep2 litEName [c] 
1296
1297 repApp :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1298 repApp (MkC x) (MkC y) = rep2 appEName [x,y] 
1299
1300 repLam :: Core [TH.PatQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1301 repLam (MkC ps) (MkC e) = rep2 lamEName [ps, e]
1302
1303 repTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
1304 repTup (MkC es) = rep2 tupEName [es]
1305
1306 repUnboxedTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
1307 repUnboxedTup (MkC es) = rep2 unboxedTupEName [es]
1308
1309 repCond :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1310 repCond (MkC x) (MkC y) (MkC z) = rep2 condEName [x,y,z] 
1311
1312 repLetE :: Core [TH.DecQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1313 repLetE (MkC ds) (MkC e) = rep2 letEName [ds, e] 
1314
1315 repCaseE :: Core TH.ExpQ -> Core [TH.MatchQ] -> DsM( Core TH.ExpQ)
1316 repCaseE (MkC e) (MkC ms) = rep2 caseEName [e, ms]
1317
1318 repDoE :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ)
1319 repDoE (MkC ss) = rep2 doEName [ss]
1320
1321 repComp :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ)
1322 repComp (MkC ss) = rep2 compEName [ss]
1323
1324 repListExp :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
1325 repListExp (MkC es) = rep2 listEName [es]
1326
1327 repSigExp :: Core TH.ExpQ -> Core TH.TypeQ -> DsM (Core TH.ExpQ)
1328 repSigExp (MkC e) (MkC t) = rep2 sigEName [e,t]
1329
1330 repRecCon :: Core TH.Name -> Core [TH.Q TH.FieldExp]-> DsM (Core TH.ExpQ)
1331 repRecCon (MkC c) (MkC fs) = rep2 recConEName [c,fs]
1332
1333 repRecUpd :: Core TH.ExpQ -> Core [TH.Q TH.FieldExp] -> DsM (Core TH.ExpQ)
1334 repRecUpd (MkC e) (MkC fs) = rep2 recUpdEName [e,fs]
1335
1336 repFieldExp :: Core TH.Name -> Core TH.ExpQ -> DsM (Core (TH.Q TH.FieldExp))
1337 repFieldExp (MkC n) (MkC x) = rep2 fieldExpName [n,x]
1338
1339 repInfixApp :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1340 repInfixApp (MkC x) (MkC y) (MkC z) = rep2 infixAppName [x,y,z]
1341
1342 repSectionL :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1343 repSectionL (MkC x) (MkC y) = rep2 sectionLName [x,y]
1344
1345 repSectionR :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1346 repSectionR (MkC x) (MkC y) = rep2 sectionRName [x,y]
1347
1348 ------------ Right hand sides (guarded expressions) ----
1349 repGuarded :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.BodyQ)
1350 repGuarded (MkC pairs) = rep2 guardedBName [pairs]
1351
1352 repNormal :: Core TH.ExpQ -> DsM (Core TH.BodyQ)
1353 repNormal (MkC e) = rep2 normalBName [e]
1354
1355 ------------ Guards ----
1356 repLNormalGE :: LHsExpr Name -> LHsExpr Name -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
1357 repLNormalGE g e = do g' <- repLE g
1358                       e' <- repLE e
1359                       repNormalGE g' e'
1360
1361 repNormalGE :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
1362 repNormalGE (MkC g) (MkC e) = rep2 normalGEName [g, e]
1363
1364 repPatGE :: Core [TH.StmtQ] -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
1365 repPatGE (MkC ss) (MkC e) = rep2 patGEName [ss, e]
1366
1367 ------------- Stmts -------------------
1368 repBindSt :: Core TH.PatQ -> Core TH.ExpQ -> DsM (Core TH.StmtQ)
1369 repBindSt (MkC p) (MkC e) = rep2 bindSName [p,e]
1370
1371 repLetSt :: Core [TH.DecQ] -> DsM (Core TH.StmtQ)
1372 repLetSt (MkC ds) = rep2 letSName [ds]
1373
1374 repNoBindSt :: Core TH.ExpQ -> DsM (Core TH.StmtQ)
1375 repNoBindSt (MkC e) = rep2 noBindSName [e]
1376
1377 -------------- Range (Arithmetic sequences) -----------
1378 repFrom :: Core TH.ExpQ -> DsM (Core TH.ExpQ)
1379 repFrom (MkC x) = rep2 fromEName [x]
1380
1381 repFromThen :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1382 repFromThen (MkC x) (MkC y) = rep2 fromThenEName [x,y]
1383
1384 repFromTo :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1385 repFromTo (MkC x) (MkC y) = rep2 fromToEName [x,y]
1386
1387 repFromThenTo :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1388 repFromThenTo (MkC x) (MkC y) (MkC z) = rep2 fromThenToEName [x,y,z]
1389
1390 ------------ Match and Clause Tuples -----------
1391 repMatch :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.MatchQ)
1392 repMatch (MkC p) (MkC bod) (MkC ds) = rep2 matchName [p, bod, ds]
1393
1394 repClause :: Core [TH.PatQ] -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.ClauseQ)
1395 repClause (MkC ps) (MkC bod) (MkC ds) = rep2 clauseName [ps, bod, ds]
1396
1397 -------------- Dec -----------------------------
1398 repVal :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ)
1399 repVal (MkC p) (MkC b) (MkC ds) = rep2 valDName [p, b, ds]
1400
1401 repFun :: Core TH.Name -> Core [TH.ClauseQ] -> DsM (Core TH.DecQ)  
1402 repFun (MkC nm) (MkC b) = rep2 funDName [nm, b]
1403
1404 repData :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr] 
1405         -> Maybe (Core [TH.TypeQ])
1406         -> Core [TH.ConQ] -> Core [TH.Name] -> DsM (Core TH.DecQ)
1407 repData (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC cons) (MkC derivs)
1408   = rep2 dataDName [cxt, nm, tvs, cons, derivs]
1409 repData (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC cons) (MkC derivs)
1410   = rep2 dataInstDName [cxt, nm, tys, cons, derivs]
1411
1412 repNewtype :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr] 
1413            -> Maybe (Core [TH.TypeQ])
1414            -> Core TH.ConQ -> Core [TH.Name] -> DsM (Core TH.DecQ)
1415 repNewtype (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC con) (MkC derivs)
1416   = rep2 newtypeDName [cxt, nm, tvs, con, derivs]
1417 repNewtype (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC con) (MkC derivs)
1418   = rep2 newtypeInstDName [cxt, nm, tys, con, derivs]
1419
1420 repTySyn :: Core TH.Name -> Core [TH.TyVarBndr] 
1421          -> Maybe (Core [TH.TypeQ])
1422          -> Core TH.TypeQ -> DsM (Core TH.DecQ)
1423 repTySyn (MkC nm) (MkC tvs) Nothing (MkC rhs) 
1424   = rep2 tySynDName [nm, tvs, rhs]
1425 repTySyn (MkC nm) (MkC _) (Just (MkC tys)) (MkC rhs) 
1426   = rep2 tySynInstDName [nm, tys, rhs]
1427
1428 repInst :: Core TH.CxtQ -> Core TH.TypeQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ)
1429 repInst (MkC cxt) (MkC ty) (MkC ds) = rep2 instanceDName [cxt, ty, ds]
1430
1431 repClass :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr] 
1432          -> Core [TH.FunDep] -> Core [TH.DecQ] 
1433          -> DsM (Core TH.DecQ)
1434 repClass (MkC cxt) (MkC cls) (MkC tvs) (MkC fds) (MkC ds) 
1435   = rep2 classDName [cxt, cls, tvs, fds, ds]
1436
1437 repPragInl :: Core TH.Name -> Core TH.InlineSpecQ -> DsM (Core TH.DecQ)
1438 repPragInl (MkC nm) (MkC ispec) = rep2 pragInlDName [nm, ispec]
1439
1440 repPragSpec :: Core TH.Name -> Core TH.TypeQ -> DsM (Core TH.DecQ)
1441 repPragSpec (MkC nm) (MkC ty) = rep2 pragSpecDName [nm, ty]
1442
1443 repPragSpecInl :: Core TH.Name -> Core TH.TypeQ -> Core TH.InlineSpecQ 
1444                -> DsM (Core TH.DecQ)
1445 repPragSpecInl (MkC nm) (MkC ty) (MkC ispec) 
1446   = rep2 pragSpecInlDName [nm, ty, ispec]
1447
1448 repFamilyNoKind :: Core TH.FamFlavour -> Core TH.Name -> Core [TH.TyVarBndr] 
1449                 -> DsM (Core TH.DecQ)
1450 repFamilyNoKind (MkC flav) (MkC nm) (MkC tvs)
1451     = rep2 familyNoKindDName [flav, nm, tvs]
1452
1453 repFamilyKind :: Core TH.FamFlavour -> Core TH.Name -> Core [TH.TyVarBndr] 
1454               -> Core TH.Kind
1455               -> DsM (Core TH.DecQ)
1456 repFamilyKind (MkC flav) (MkC nm) (MkC tvs) (MkC ki)
1457     = rep2 familyKindDName [flav, nm, tvs, ki]
1458
1459 repInlineSpecNoPhase :: Core Bool -> Core Bool -> DsM (Core TH.InlineSpecQ)
1460 repInlineSpecNoPhase (MkC inline) (MkC conlike) 
1461   = rep2 inlineSpecNoPhaseName [inline, conlike]
1462
1463 repInlineSpecPhase :: Core Bool -> Core Bool -> Core Bool -> Core Int
1464                    -> DsM (Core TH.InlineSpecQ)
1465 repInlineSpecPhase (MkC inline) (MkC conlike) (MkC beforeFrom) (MkC phase)
1466   = rep2 inlineSpecPhaseName [inline, conlike, beforeFrom, phase]
1467
1468 repFunDep :: Core [TH.Name] -> Core [TH.Name] -> DsM (Core TH.FunDep)
1469 repFunDep (MkC xs) (MkC ys) = rep2 funDepName [xs, ys]
1470
1471 repProto :: Core TH.Name -> Core TH.TypeQ -> DsM (Core TH.DecQ)
1472 repProto (MkC s) (MkC ty) = rep2 sigDName [s, ty]
1473
1474 repCtxt :: Core [TH.PredQ] -> DsM (Core TH.CxtQ)
1475 repCtxt (MkC tys) = rep2 cxtName [tys]
1476
1477 repClassP :: Core TH.Name -> Core [TH.TypeQ] -> DsM (Core TH.PredQ)
1478 repClassP (MkC cla) (MkC tys) = rep2 classPName [cla, tys]
1479
1480 repEqualP :: Core TH.TypeQ -> Core TH.TypeQ -> DsM (Core TH.PredQ)
1481 repEqualP (MkC ty1) (MkC ty2) = rep2 equalPName [ty1, ty2]
1482
1483 repConstr :: Core TH.Name -> HsConDeclDetails Name
1484           -> DsM (Core TH.ConQ)
1485 repConstr con (PrefixCon ps)
1486     = do arg_tys  <- mapM repBangTy ps
1487          arg_tys1 <- coreList strictTypeQTyConName arg_tys
1488          rep2 normalCName [unC con, unC arg_tys1]
1489 repConstr con (RecCon ips)
1490     = do arg_vs   <- mapM lookupLOcc (map cd_fld_name ips)
1491          arg_tys  <- mapM repBangTy (map cd_fld_type ips)
1492          arg_vtys <- zipWithM (\x y -> rep2 varStrictTypeName [unC x, unC y])
1493                               arg_vs arg_tys
1494          arg_vtys' <- coreList varStrictTypeQTyConName arg_vtys
1495          rep2 recCName [unC con, unC arg_vtys']
1496 repConstr con (InfixCon st1 st2)
1497     = do arg1 <- repBangTy st1
1498          arg2 <- repBangTy st2
1499          rep2 infixCName [unC arg1, unC con, unC arg2]
1500
1501 ------------ Types -------------------
1502
1503 repTForall :: Core [TH.TyVarBndr] -> Core TH.CxtQ -> Core TH.TypeQ 
1504            -> DsM (Core TH.TypeQ)
1505 repTForall (MkC tvars) (MkC ctxt) (MkC ty)
1506     = rep2 forallTName [tvars, ctxt, ty]
1507
1508 repTvar :: Core TH.Name -> DsM (Core TH.TypeQ)
1509 repTvar (MkC s) = rep2 varTName [s]
1510
1511 repTapp :: Core TH.TypeQ -> Core TH.TypeQ -> DsM (Core TH.TypeQ)
1512 repTapp (MkC t1) (MkC t2) = rep2 appTName [t1, t2]
1513
1514 repTapps :: Core TH.TypeQ -> [Core TH.TypeQ] -> DsM (Core TH.TypeQ)
1515 repTapps f []     = return f
1516 repTapps f (t:ts) = do { f1 <- repTapp f t; repTapps f1 ts }
1517
1518 repTSig :: Core TH.TypeQ -> Core TH.Kind -> DsM (Core TH.TypeQ)
1519 repTSig (MkC ty) (MkC ki) = rep2 sigTName [ty, ki]
1520
1521 --------- Type constructors --------------
1522
1523 repNamedTyCon :: Core TH.Name -> DsM (Core TH.TypeQ)
1524 repNamedTyCon (MkC s) = rep2 conTName [s]
1525
1526 repTupleTyCon :: Int -> DsM (Core TH.TypeQ)
1527 -- Note: not Core Int; it's easier to be direct here
1528 repTupleTyCon i = rep2 tupleTName [mkIntExprInt i]
1529
1530 repUnboxedTupleTyCon :: Int -> DsM (Core TH.TypeQ)
1531 -- Note: not Core Int; it's easier to be direct here
1532 repUnboxedTupleTyCon i = rep2 unboxedTupleTName [mkIntExprInt i]
1533
1534 repArrowTyCon :: DsM (Core TH.TypeQ)
1535 repArrowTyCon = rep2 arrowTName []
1536
1537 repListTyCon :: DsM (Core TH.TypeQ)
1538 repListTyCon = rep2 listTName []
1539
1540 ------------ Kinds -------------------
1541
1542 repPlainTV :: Core TH.Name -> DsM (Core TH.TyVarBndr)
1543 repPlainTV (MkC nm) = rep2 plainTVName [nm]
1544
1545 repKindedTV :: Core TH.Name -> Core TH.Kind -> DsM (Core TH.TyVarBndr)
1546 repKindedTV (MkC nm) (MkC ki) = rep2 kindedTVName [nm, ki]
1547
1548 repStarK :: DsM (Core TH.Kind)
1549 repStarK = rep2 starKName []
1550
1551 repArrowK :: Core TH.Kind -> Core TH.Kind -> DsM (Core TH.Kind)
1552 repArrowK (MkC ki1) (MkC ki2) = rep2 arrowKName [ki1, ki2]
1553
1554 ----------------------------------------------------------
1555 --              Literals
1556
1557 repLiteral :: HsLit -> DsM (Core TH.Lit)
1558 repLiteral lit 
1559   = do lit' <- case lit of
1560                    HsIntPrim i    -> mk_integer i
1561                    HsWordPrim w   -> mk_integer w
1562                    HsInt i        -> mk_integer i
1563                    HsFloatPrim r  -> mk_rational r
1564                    HsDoublePrim r -> mk_rational r
1565                    _ -> return lit
1566        lit_expr <- dsLit lit'
1567        case mb_lit_name of
1568           Just lit_name -> rep2 lit_name [lit_expr]
1569           Nothing -> notHandled "Exotic literal" (ppr lit)
1570   where
1571     mb_lit_name = case lit of
1572                  HsInteger _ _  -> Just integerLName
1573                  HsInt     _    -> Just integerLName
1574                  HsIntPrim _    -> Just intPrimLName
1575                  HsWordPrim _   -> Just wordPrimLName
1576                  HsFloatPrim _  -> Just floatPrimLName
1577                  HsDoublePrim _ -> Just doublePrimLName
1578                  HsChar _       -> Just charLName
1579                  HsString _     -> Just stringLName
1580                  HsRat _ _      -> Just rationalLName
1581                  _              -> Nothing
1582
1583 mk_integer :: Integer -> DsM HsLit
1584 mk_integer  i = do integer_ty <- lookupType integerTyConName
1585                    return $ HsInteger i integer_ty
1586 mk_rational :: FractionalLit -> DsM HsLit
1587 mk_rational r = do rat_ty <- lookupType rationalTyConName
1588                    return $ HsRat r rat_ty
1589 mk_string :: FastString -> DsM HsLit
1590 mk_string s = return $ HsString s
1591
1592 repOverloadedLiteral :: HsOverLit Name -> DsM (Core TH.Lit)
1593 repOverloadedLiteral (OverLit { ol_val = val})
1594   = do { lit <- mk_lit val; repLiteral lit }
1595         -- The type Rational will be in the environment, becuase 
1596         -- the smart constructor 'TH.Syntax.rationalL' uses it in its type,
1597         -- and rationalL is sucked in when any TH stuff is used
1598
1599 mk_lit :: OverLitVal -> DsM HsLit
1600 mk_lit (HsIntegral i)   = mk_integer  i
1601 mk_lit (HsFractional f) = mk_rational f
1602 mk_lit (HsIsString s)   = mk_string   s
1603               
1604 --------------- Miscellaneous -------------------
1605
1606 repGensym :: Core String -> DsM (Core (TH.Q TH.Name))
1607 repGensym (MkC lit_str) = rep2 newNameName [lit_str]
1608
1609 repBindQ :: Type -> Type        -- a and b
1610          -> Core (TH.Q a) -> Core (a -> TH.Q b) -> DsM (Core (TH.Q b))
1611 repBindQ ty_a ty_b (MkC x) (MkC y) 
1612   = rep2 bindQName [Type ty_a, Type ty_b, x, y] 
1613
1614 repSequenceQ :: Type -> Core [TH.Q a] -> DsM (Core (TH.Q [a]))
1615 repSequenceQ ty_a (MkC list)
1616   = rep2 sequenceQName [Type ty_a, list]
1617
1618 ------------ Lists and Tuples -------------------
1619 -- turn a list of patterns into a single pattern matching a list
1620
1621 coreList :: Name        -- Of the TyCon of the element type
1622          -> [Core a] -> DsM (Core [a])
1623 coreList tc_name es 
1624   = do { elt_ty <- lookupType tc_name; return (coreList' elt_ty es) }
1625
1626 coreList' :: Type       -- The element type
1627           -> [Core a] -> Core [a]
1628 coreList' elt_ty es = MkC (mkListExpr elt_ty (map unC es ))
1629
1630 nonEmptyCoreList :: [Core a] -> Core [a]
1631   -- The list must be non-empty so we can get the element type
1632   -- Otherwise use coreList
1633 nonEmptyCoreList []           = panic "coreList: empty argument"
1634 nonEmptyCoreList xs@(MkC x:_) = MkC (mkListExpr (exprType x) (map unC xs))
1635
1636 coreStringLit :: String -> DsM (Core String)
1637 coreStringLit s = do { z <- mkStringExpr s; return(MkC z) }
1638
1639 ------------ Bool, Literals & Variables -------------------
1640
1641 coreBool :: Bool -> Core Bool
1642 coreBool False = MkC $ mkConApp falseDataCon []
1643 coreBool True  = MkC $ mkConApp trueDataCon  []
1644
1645 coreIntLit :: Int -> DsM (Core Int)
1646 coreIntLit i = return (MkC (mkIntExprInt i))
1647
1648 coreVar :: Id -> Core TH.Name   -- The Id has type Name
1649 coreVar id = MkC (Var id)
1650
1651 ----------------- Failure -----------------------
1652 notHandled :: String -> SDoc -> DsM a
1653 notHandled what doc = failWithDs msg
1654   where
1655     msg = hang (text what <+> ptext (sLit "not (yet) handled by Template Haskell")) 
1656              2 doc
1657
1658
1659 -- %************************************************************************
1660 -- %*                                                                   *
1661 --              The known-key names for Template Haskell
1662 -- %*                                                                   *
1663 -- %************************************************************************
1664
1665 -- To add a name, do three things
1666 -- 
1667 --  1) Allocate a key
1668 --  2) Make a "Name"
1669 --  3) Add the name to knownKeyNames
1670
1671 templateHaskellNames :: [Name]
1672 -- The names that are implicitly mentioned by ``bracket''
1673 -- Should stay in sync with the import list of DsMeta
1674
1675 templateHaskellNames = [
1676     returnQName, bindQName, sequenceQName, newNameName, liftName,
1677     mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName, mkNameLName, 
1678     liftStringName,
1679  
1680     -- Lit
1681     charLName, stringLName, integerLName, intPrimLName, wordPrimLName,
1682     floatPrimLName, doublePrimLName, rationalLName, 
1683     -- Pat
1684     litPName, varPName, tupPName, unboxedTupPName,
1685     conPName, tildePName, bangPName, infixPName,
1686     asPName, wildPName, recPName, listPName, sigPName, viewPName,
1687     -- FieldPat
1688     fieldPatName,
1689     -- Match
1690     matchName,
1691     -- Clause
1692     clauseName,
1693     -- Exp
1694     varEName, conEName, litEName, appEName, infixEName,
1695     infixAppName, sectionLName, sectionRName, lamEName,
1696     tupEName, unboxedTupEName,
1697     condEName, letEName, caseEName, doEName, compEName,
1698     fromEName, fromThenEName, fromToEName, fromThenToEName,
1699     listEName, sigEName, recConEName, recUpdEName,
1700     -- FieldExp
1701     fieldExpName,
1702     -- Body
1703     guardedBName, normalBName,
1704     -- Guard
1705     normalGEName, patGEName,
1706     -- Stmt
1707     bindSName, letSName, noBindSName, parSName,
1708     -- Dec
1709     funDName, valDName, dataDName, newtypeDName, tySynDName,
1710     classDName, instanceDName, sigDName, forImpDName, 
1711     pragInlDName, pragSpecDName, pragSpecInlDName,
1712     familyNoKindDName, familyKindDName, dataInstDName, newtypeInstDName,
1713     tySynInstDName, 
1714     -- Cxt
1715     cxtName,
1716     -- Pred
1717     classPName, equalPName,
1718     -- Strict
1719     isStrictName, notStrictName,
1720     -- Con
1721     normalCName, recCName, infixCName, forallCName,
1722     -- StrictType
1723     strictTypeName,
1724     -- VarStrictType
1725     varStrictTypeName,
1726     -- Type
1727     forallTName, varTName, conTName, appTName,
1728     tupleTName, unboxedTupleTName, arrowTName, listTName, sigTName,
1729     -- TyVarBndr
1730     plainTVName, kindedTVName,
1731     -- Kind
1732     starKName, arrowKName,
1733     -- Callconv
1734     cCallName, stdCallName,
1735     -- Safety
1736     unsafeName,
1737     safeName,
1738     threadsafeName,
1739     interruptibleName,
1740     -- InlineSpec
1741     inlineSpecNoPhaseName, inlineSpecPhaseName,
1742     -- FunDep
1743     funDepName,
1744     -- FamFlavour
1745     typeFamName, dataFamName,
1746
1747     -- And the tycons
1748     qTyConName, nameTyConName, patTyConName, fieldPatTyConName, matchQTyConName,
1749     clauseQTyConName, expQTyConName, fieldExpTyConName, predTyConName,
1750     stmtQTyConName, decQTyConName, conQTyConName, strictTypeQTyConName,
1751     varStrictTypeQTyConName, typeQTyConName, expTyConName, decTyConName,
1752     typeTyConName, tyVarBndrTyConName, matchTyConName, clauseTyConName,
1753     patQTyConName, fieldPatQTyConName, fieldExpQTyConName, funDepTyConName,
1754     predQTyConName, decsQTyConName, 
1755
1756     -- Quasiquoting
1757     quoteDecName, quoteTypeName, quoteExpName, quotePatName]
1758
1759 thSyn, thLib, qqLib :: Module
1760 thSyn = mkTHModule (fsLit "Language.Haskell.TH.Syntax")
1761 thLib = mkTHModule (fsLit "Language.Haskell.TH.Lib")
1762 qqLib = mkTHModule (fsLit "Language.Haskell.TH.Quote")
1763
1764 mkTHModule :: FastString -> Module
1765 mkTHModule m = mkModule thPackageId (mkModuleNameFS m)
1766
1767 libFun, libTc, thFun, thTc, qqFun :: FastString -> Unique -> Name
1768 libFun = mk_known_key_name OccName.varName thLib
1769 libTc  = mk_known_key_name OccName.tcName  thLib
1770 thFun  = mk_known_key_name OccName.varName thSyn
1771 thTc   = mk_known_key_name OccName.tcName  thSyn
1772 qqFun  = mk_known_key_name OccName.varName qqLib
1773
1774 -------------------- TH.Syntax -----------------------
1775 qTyConName, nameTyConName, fieldExpTyConName, patTyConName,
1776     fieldPatTyConName, expTyConName, decTyConName, typeTyConName,
1777     tyVarBndrTyConName, matchTyConName, clauseTyConName, funDepTyConName,
1778     predTyConName :: Name 
1779 qTyConName        = thTc (fsLit "Q")            qTyConKey
1780 nameTyConName     = thTc (fsLit "Name")         nameTyConKey
1781 fieldExpTyConName = thTc (fsLit "FieldExp")     fieldExpTyConKey
1782 patTyConName      = thTc (fsLit "Pat")          patTyConKey
1783 fieldPatTyConName = thTc (fsLit "FieldPat")     fieldPatTyConKey
1784 expTyConName      = thTc (fsLit "Exp")          expTyConKey
1785 decTyConName      = thTc (fsLit "Dec")          decTyConKey
1786 typeTyConName     = thTc (fsLit "Type")         typeTyConKey
1787 tyVarBndrTyConName= thTc (fsLit "TyVarBndr")    tyVarBndrTyConKey
1788 matchTyConName    = thTc (fsLit "Match")        matchTyConKey
1789 clauseTyConName   = thTc (fsLit "Clause")       clauseTyConKey
1790 funDepTyConName   = thTc (fsLit "FunDep")       funDepTyConKey
1791 predTyConName     = thTc (fsLit "Pred")         predTyConKey
1792
1793 returnQName, bindQName, sequenceQName, newNameName, liftName,
1794     mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName,
1795     mkNameLName, liftStringName :: Name
1796 returnQName    = thFun (fsLit "returnQ")   returnQIdKey
1797 bindQName      = thFun (fsLit "bindQ")     bindQIdKey
1798 sequenceQName  = thFun (fsLit "sequenceQ") sequenceQIdKey
1799 newNameName    = thFun (fsLit "newName")   newNameIdKey
1800 liftName       = thFun (fsLit "lift")      liftIdKey
1801 liftStringName = thFun (fsLit "liftString")  liftStringIdKey
1802 mkNameName     = thFun (fsLit "mkName")     mkNameIdKey
1803 mkNameG_vName  = thFun (fsLit "mkNameG_v")  mkNameG_vIdKey
1804 mkNameG_dName  = thFun (fsLit "mkNameG_d")  mkNameG_dIdKey
1805 mkNameG_tcName = thFun (fsLit "mkNameG_tc") mkNameG_tcIdKey
1806 mkNameLName    = thFun (fsLit "mkNameL")    mkNameLIdKey
1807
1808
1809 -------------------- TH.Lib -----------------------
1810 -- data Lit = ...
1811 charLName, stringLName, integerLName, intPrimLName, wordPrimLName,
1812     floatPrimLName, doublePrimLName, rationalLName :: Name
1813 charLName       = libFun (fsLit "charL")       charLIdKey
1814 stringLName     = libFun (fsLit "stringL")     stringLIdKey
1815 integerLName    = libFun (fsLit "integerL")    integerLIdKey
1816 intPrimLName    = libFun (fsLit "intPrimL")    intPrimLIdKey
1817 wordPrimLName   = libFun (fsLit "wordPrimL")   wordPrimLIdKey
1818 floatPrimLName  = libFun (fsLit "floatPrimL")  floatPrimLIdKey
1819 doublePrimLName = libFun (fsLit "doublePrimL") doublePrimLIdKey
1820 rationalLName   = libFun (fsLit "rationalL")     rationalLIdKey
1821
1822 -- data Pat = ...
1823 litPName, varPName, tupPName, unboxedTupPName, conPName, infixPName, tildePName, bangPName,
1824     asPName, wildPName, recPName, listPName, sigPName, viewPName :: Name
1825 litPName   = libFun (fsLit "litP")   litPIdKey
1826 varPName   = libFun (fsLit "varP")   varPIdKey
1827 tupPName   = libFun (fsLit "tupP")   tupPIdKey
1828 unboxedTupPName = libFun (fsLit "unboxedTupP") unboxedTupPIdKey
1829 conPName   = libFun (fsLit "conP")   conPIdKey
1830 infixPName = libFun (fsLit "infixP") infixPIdKey
1831 tildePName = libFun (fsLit "tildeP") tildePIdKey
1832 bangPName  = libFun (fsLit "bangP")  bangPIdKey
1833 asPName    = libFun (fsLit "asP")    asPIdKey
1834 wildPName  = libFun (fsLit "wildP")  wildPIdKey
1835 recPName   = libFun (fsLit "recP")   recPIdKey
1836 listPName  = libFun (fsLit "listP")  listPIdKey
1837 sigPName   = libFun (fsLit "sigP")   sigPIdKey
1838 viewPName  = libFun (fsLit "viewP")  viewPIdKey
1839
1840 -- type FieldPat = ...
1841 fieldPatName :: Name
1842 fieldPatName = libFun (fsLit "fieldPat") fieldPatIdKey
1843
1844 -- data Match = ...
1845 matchName :: Name
1846 matchName = libFun (fsLit "match") matchIdKey
1847
1848 -- data Clause = ...
1849 clauseName :: Name
1850 clauseName = libFun (fsLit "clause") clauseIdKey
1851
1852 -- data Exp = ...
1853 varEName, conEName, litEName, appEName, infixEName, infixAppName,
1854     sectionLName, sectionRName, lamEName, tupEName, unboxedTupEName, condEName,
1855     letEName, caseEName, doEName, compEName :: Name
1856 varEName        = libFun (fsLit "varE")        varEIdKey
1857 conEName        = libFun (fsLit "conE")        conEIdKey
1858 litEName        = libFun (fsLit "litE")        litEIdKey
1859 appEName        = libFun (fsLit "appE")        appEIdKey
1860 infixEName      = libFun (fsLit "infixE")      infixEIdKey
1861 infixAppName    = libFun (fsLit "infixApp")    infixAppIdKey
1862 sectionLName    = libFun (fsLit "sectionL")    sectionLIdKey
1863 sectionRName    = libFun (fsLit "sectionR")    sectionRIdKey
1864 lamEName        = libFun (fsLit "lamE")        lamEIdKey
1865 tupEName        = libFun (fsLit "tupE")        tupEIdKey
1866 unboxedTupEName = libFun (fsLit "unboxedTupE") unboxedTupEIdKey
1867 condEName       = libFun (fsLit "condE")       condEIdKey
1868 letEName        = libFun (fsLit "letE")        letEIdKey
1869 caseEName       = libFun (fsLit "caseE")       caseEIdKey
1870 doEName         = libFun (fsLit "doE")         doEIdKey
1871 compEName       = libFun (fsLit "compE")       compEIdKey
1872 -- ArithSeq skips a level
1873 fromEName, fromThenEName, fromToEName, fromThenToEName :: Name
1874 fromEName       = libFun (fsLit "fromE")       fromEIdKey
1875 fromThenEName   = libFun (fsLit "fromThenE")   fromThenEIdKey
1876 fromToEName     = libFun (fsLit "fromToE")     fromToEIdKey
1877 fromThenToEName = libFun (fsLit "fromThenToE") fromThenToEIdKey
1878 -- end ArithSeq
1879 listEName, sigEName, recConEName, recUpdEName :: Name
1880 listEName       = libFun (fsLit "listE")       listEIdKey
1881 sigEName        = libFun (fsLit "sigE")        sigEIdKey
1882 recConEName     = libFun (fsLit "recConE")     recConEIdKey
1883 recUpdEName     = libFun (fsLit "recUpdE")     recUpdEIdKey
1884
1885 -- type FieldExp = ...
1886 fieldExpName :: Name
1887 fieldExpName = libFun (fsLit "fieldExp") fieldExpIdKey
1888
1889 -- data Body = ...
1890 guardedBName, normalBName :: Name
1891 guardedBName = libFun (fsLit "guardedB") guardedBIdKey
1892 normalBName  = libFun (fsLit "normalB")  normalBIdKey
1893
1894 -- data Guard = ...
1895 normalGEName, patGEName :: Name
1896 normalGEName = libFun (fsLit "normalGE") normalGEIdKey
1897 patGEName    = libFun (fsLit "patGE")    patGEIdKey
1898
1899 -- data Stmt = ...
1900 bindSName, letSName, noBindSName, parSName :: Name
1901 bindSName   = libFun (fsLit "bindS")   bindSIdKey
1902 letSName    = libFun (fsLit "letS")    letSIdKey
1903 noBindSName = libFun (fsLit "noBindS") noBindSIdKey
1904 parSName    = libFun (fsLit "parS")    parSIdKey
1905
1906 -- data Dec = ...
1907 funDName, valDName, dataDName, newtypeDName, tySynDName, classDName,
1908     instanceDName, sigDName, forImpDName, pragInlDName, pragSpecDName,
1909     pragSpecInlDName, familyNoKindDName, familyKindDName, dataInstDName,
1910     newtypeInstDName, tySynInstDName :: Name
1911 funDName         = libFun (fsLit "funD")         funDIdKey
1912 valDName         = libFun (fsLit "valD")         valDIdKey
1913 dataDName        = libFun (fsLit "dataD")        dataDIdKey
1914 newtypeDName     = libFun (fsLit "newtypeD")     newtypeDIdKey
1915 tySynDName       = libFun (fsLit "tySynD")       tySynDIdKey
1916 classDName       = libFun (fsLit "classD")       classDIdKey
1917 instanceDName    = libFun (fsLit "instanceD")    instanceDIdKey
1918 sigDName         = libFun (fsLit "sigD")         sigDIdKey
1919 forImpDName      = libFun (fsLit "forImpD")      forImpDIdKey
1920 pragInlDName     = libFun (fsLit "pragInlD")     pragInlDIdKey
1921 pragSpecDName    = libFun (fsLit "pragSpecD")    pragSpecDIdKey
1922 pragSpecInlDName = libFun (fsLit "pragSpecInlD") pragSpecInlDIdKey
1923 familyNoKindDName= libFun (fsLit "familyNoKindD")familyNoKindDIdKey
1924 familyKindDName  = libFun (fsLit "familyKindD")  familyKindDIdKey
1925 dataInstDName    = libFun (fsLit "dataInstD")    dataInstDIdKey
1926 newtypeInstDName = libFun (fsLit "newtypeInstD") newtypeInstDIdKey
1927 tySynInstDName   = libFun (fsLit "tySynInstD")   tySynInstDIdKey
1928
1929 -- type Ctxt = ...
1930 cxtName :: Name
1931 cxtName = libFun (fsLit "cxt") cxtIdKey
1932
1933 -- data Pred = ...
1934 classPName, equalPName :: Name
1935 classPName = libFun (fsLit "classP") classPIdKey
1936 equalPName = libFun (fsLit "equalP") equalPIdKey
1937
1938 -- data Strict = ...
1939 isStrictName, notStrictName :: Name
1940 isStrictName      = libFun  (fsLit "isStrict")      isStrictKey
1941 notStrictName     = libFun  (fsLit "notStrict")     notStrictKey
1942
1943 -- data Con = ...
1944 normalCName, recCName, infixCName, forallCName :: Name
1945 normalCName = libFun (fsLit "normalC") normalCIdKey
1946 recCName    = libFun (fsLit "recC")    recCIdKey
1947 infixCName  = libFun (fsLit "infixC")  infixCIdKey
1948 forallCName  = libFun (fsLit "forallC")  forallCIdKey
1949
1950 -- type StrictType = ...
1951 strictTypeName :: Name
1952 strictTypeName    = libFun  (fsLit "strictType")    strictTKey
1953
1954 -- type VarStrictType = ...
1955 varStrictTypeName :: Name
1956 varStrictTypeName = libFun  (fsLit "varStrictType") varStrictTKey
1957
1958 -- data Type = ...
1959 forallTName, varTName, conTName, tupleTName, unboxedTupleTName, arrowTName,
1960     listTName, appTName, sigTName :: Name
1961 forallTName = libFun (fsLit "forallT") forallTIdKey
1962 varTName    = libFun (fsLit "varT")    varTIdKey
1963 conTName    = libFun (fsLit "conT")    conTIdKey
1964 tupleTName  = libFun (fsLit "tupleT")  tupleTIdKey
1965 unboxedTupleTName = libFun (fsLit "unboxedTupleT")  unboxedTupleTIdKey
1966 arrowTName  = libFun (fsLit "arrowT")  arrowTIdKey
1967 listTName   = libFun (fsLit "listT")   listTIdKey
1968 appTName    = libFun (fsLit "appT")    appTIdKey
1969 sigTName    = libFun (fsLit "sigT")    sigTIdKey
1970
1971 -- data TyVarBndr = ...
1972 plainTVName, kindedTVName :: Name
1973 plainTVName  = libFun (fsLit "plainTV")  plainTVIdKey
1974 kindedTVName = libFun (fsLit "kindedTV") kindedTVIdKey
1975
1976 -- data Kind = ...
1977 starKName, arrowKName :: Name
1978 starKName  = libFun (fsLit "starK")   starKIdKey
1979 arrowKName = libFun (fsLit "arrowK")  arrowKIdKey
1980
1981 -- data Callconv = ...
1982 cCallName, stdCallName :: Name
1983 cCallName = libFun (fsLit "cCall") cCallIdKey
1984 stdCallName = libFun (fsLit "stdCall") stdCallIdKey
1985
1986 -- data Safety = ...
1987 unsafeName, safeName, threadsafeName, interruptibleName :: Name
1988 unsafeName     = libFun (fsLit "unsafe") unsafeIdKey
1989 safeName       = libFun (fsLit "safe") safeIdKey
1990 threadsafeName = libFun (fsLit "threadsafe") threadsafeIdKey
1991 interruptibleName = libFun (fsLit "interruptible") interruptibleIdKey
1992
1993 -- data InlineSpec = ...
1994 inlineSpecNoPhaseName, inlineSpecPhaseName :: Name
1995 inlineSpecNoPhaseName = libFun (fsLit "inlineSpecNoPhase") inlineSpecNoPhaseIdKey
1996 inlineSpecPhaseName   = libFun (fsLit "inlineSpecPhase")   inlineSpecPhaseIdKey
1997
1998 -- data FunDep = ...
1999 funDepName :: Name
2000 funDepName     = libFun (fsLit "funDep") funDepIdKey
2001
2002 -- data FamFlavour = ...
2003 typeFamName, dataFamName :: Name
2004 typeFamName = libFun (fsLit "typeFam") typeFamIdKey
2005 dataFamName = libFun (fsLit "dataFam") dataFamIdKey
2006
2007 matchQTyConName, clauseQTyConName, expQTyConName, stmtQTyConName,
2008     decQTyConName, conQTyConName, strictTypeQTyConName,
2009     varStrictTypeQTyConName, typeQTyConName, fieldExpQTyConName,
2010     patQTyConName, fieldPatQTyConName, predQTyConName, decsQTyConName :: Name
2011 matchQTyConName         = libTc (fsLit "MatchQ")        matchQTyConKey
2012 clauseQTyConName        = libTc (fsLit "ClauseQ")       clauseQTyConKey
2013 expQTyConName           = libTc (fsLit "ExpQ")          expQTyConKey
2014 stmtQTyConName          = libTc (fsLit "StmtQ")         stmtQTyConKey
2015 decQTyConName           = libTc (fsLit "DecQ")          decQTyConKey
2016 decsQTyConName          = libTc (fsLit "DecsQ")          decsQTyConKey  -- Q [Dec]
2017 conQTyConName           = libTc (fsLit "ConQ")           conQTyConKey
2018 strictTypeQTyConName    = libTc (fsLit "StrictTypeQ")    strictTypeQTyConKey
2019 varStrictTypeQTyConName = libTc (fsLit "VarStrictTypeQ") varStrictTypeQTyConKey
2020 typeQTyConName          = libTc (fsLit "TypeQ")          typeQTyConKey
2021 fieldExpQTyConName      = libTc (fsLit "FieldExpQ")      fieldExpQTyConKey
2022 patQTyConName           = libTc (fsLit "PatQ")           patQTyConKey
2023 fieldPatQTyConName      = libTc (fsLit "FieldPatQ")      fieldPatQTyConKey
2024 predQTyConName          = libTc (fsLit "PredQ")          predQTyConKey
2025
2026 -- quasiquoting
2027 quoteExpName, quotePatName, quoteDecName, quoteTypeName :: Name
2028 quoteExpName        = qqFun (fsLit "quoteExp")  quoteExpKey
2029 quotePatName        = qqFun (fsLit "quotePat")  quotePatKey
2030 quoteDecName        = qqFun (fsLit "quoteDec")  quoteDecKey
2031 quoteTypeName       = qqFun (fsLit "quoteType") quoteTypeKey
2032
2033 -- TyConUniques available: 200-299
2034 -- Check in PrelNames if you want to change this
2035
2036 expTyConKey, matchTyConKey, clauseTyConKey, qTyConKey, expQTyConKey,
2037     decQTyConKey, patTyConKey, matchQTyConKey, clauseQTyConKey,
2038     stmtQTyConKey, conQTyConKey, typeQTyConKey, typeTyConKey, tyVarBndrTyConKey,
2039     decTyConKey, varStrictTypeQTyConKey, strictTypeQTyConKey,
2040     fieldExpTyConKey, fieldPatTyConKey, nameTyConKey, patQTyConKey,
2041     fieldPatQTyConKey, fieldExpQTyConKey, funDepTyConKey, predTyConKey,
2042     predQTyConKey, decsQTyConKey :: Unique
2043 expTyConKey             = mkPreludeTyConUnique 200
2044 matchTyConKey           = mkPreludeTyConUnique 201
2045 clauseTyConKey          = mkPreludeTyConUnique 202
2046 qTyConKey               = mkPreludeTyConUnique 203
2047 expQTyConKey            = mkPreludeTyConUnique 204
2048 decQTyConKey            = mkPreludeTyConUnique 205
2049 patTyConKey             = mkPreludeTyConUnique 206
2050 matchQTyConKey          = mkPreludeTyConUnique 207
2051 clauseQTyConKey         = mkPreludeTyConUnique 208
2052 stmtQTyConKey           = mkPreludeTyConUnique 209
2053 conQTyConKey            = mkPreludeTyConUnique 210
2054 typeQTyConKey           = mkPreludeTyConUnique 211
2055 typeTyConKey            = mkPreludeTyConUnique 212
2056 decTyConKey             = mkPreludeTyConUnique 213
2057 varStrictTypeQTyConKey  = mkPreludeTyConUnique 214
2058 strictTypeQTyConKey     = mkPreludeTyConUnique 215
2059 fieldExpTyConKey        = mkPreludeTyConUnique 216
2060 fieldPatTyConKey        = mkPreludeTyConUnique 217
2061 nameTyConKey            = mkPreludeTyConUnique 218
2062 patQTyConKey            = mkPreludeTyConUnique 219
2063 fieldPatQTyConKey       = mkPreludeTyConUnique 220
2064 fieldExpQTyConKey       = mkPreludeTyConUnique 221
2065 funDepTyConKey          = mkPreludeTyConUnique 222
2066 predTyConKey            = mkPreludeTyConUnique 223
2067 predQTyConKey           = mkPreludeTyConUnique 224
2068 tyVarBndrTyConKey       = mkPreludeTyConUnique 225
2069 decsQTyConKey           = mkPreludeTyConUnique 226
2070
2071 -- IdUniques available: 200-399
2072 -- If you want to change this, make sure you check in PrelNames
2073
2074 returnQIdKey, bindQIdKey, sequenceQIdKey, liftIdKey, newNameIdKey,
2075     mkNameIdKey, mkNameG_vIdKey, mkNameG_dIdKey, mkNameG_tcIdKey,
2076     mkNameLIdKey :: Unique
2077 returnQIdKey        = mkPreludeMiscIdUnique 200
2078 bindQIdKey          = mkPreludeMiscIdUnique 201
2079 sequenceQIdKey      = mkPreludeMiscIdUnique 202
2080 liftIdKey           = mkPreludeMiscIdUnique 203
2081 newNameIdKey         = mkPreludeMiscIdUnique 204
2082 mkNameIdKey          = mkPreludeMiscIdUnique 205
2083 mkNameG_vIdKey       = mkPreludeMiscIdUnique 206
2084 mkNameG_dIdKey       = mkPreludeMiscIdUnique 207
2085 mkNameG_tcIdKey      = mkPreludeMiscIdUnique 208
2086 mkNameLIdKey         = mkPreludeMiscIdUnique 209
2087
2088
2089 -- data Lit = ...
2090 charLIdKey, stringLIdKey, integerLIdKey, intPrimLIdKey, wordPrimLIdKey,
2091     floatPrimLIdKey, doublePrimLIdKey, rationalLIdKey :: Unique
2092 charLIdKey        = mkPreludeMiscIdUnique 220
2093 stringLIdKey      = mkPreludeMiscIdUnique 221
2094 integerLIdKey     = mkPreludeMiscIdUnique 222
2095 intPrimLIdKey     = mkPreludeMiscIdUnique 223
2096 wordPrimLIdKey    = mkPreludeMiscIdUnique 224
2097 floatPrimLIdKey   = mkPreludeMiscIdUnique 225
2098 doublePrimLIdKey  = mkPreludeMiscIdUnique 226
2099 rationalLIdKey    = mkPreludeMiscIdUnique 227
2100
2101 liftStringIdKey :: Unique
2102 liftStringIdKey     = mkPreludeMiscIdUnique 228
2103
2104 -- data Pat = ...
2105 litPIdKey, varPIdKey, tupPIdKey, unboxedTupPIdKey, conPIdKey, infixPIdKey, tildePIdKey, bangPIdKey,
2106     asPIdKey, wildPIdKey, recPIdKey, listPIdKey, sigPIdKey, viewPIdKey :: Unique
2107 litPIdKey         = mkPreludeMiscIdUnique 240
2108 varPIdKey         = mkPreludeMiscIdUnique 241
2109 tupPIdKey         = mkPreludeMiscIdUnique 242
2110 unboxedTupPIdKey  = mkPreludeMiscIdUnique 243
2111 conPIdKey         = mkPreludeMiscIdUnique 244
2112 infixPIdKey       = mkPreludeMiscIdUnique 245
2113 tildePIdKey       = mkPreludeMiscIdUnique 246
2114 bangPIdKey        = mkPreludeMiscIdUnique 247
2115 asPIdKey          = mkPreludeMiscIdUnique 248
2116 wildPIdKey        = mkPreludeMiscIdUnique 249
2117 recPIdKey         = mkPreludeMiscIdUnique 250
2118 listPIdKey        = mkPreludeMiscIdUnique 251
2119 sigPIdKey         = mkPreludeMiscIdUnique 252
2120 viewPIdKey        = mkPreludeMiscIdUnique 253
2121
2122 -- type FieldPat = ...
2123 fieldPatIdKey :: Unique
2124 fieldPatIdKey       = mkPreludeMiscIdUnique 260
2125
2126 -- data Match = ...
2127 matchIdKey :: Unique
2128 matchIdKey          = mkPreludeMiscIdUnique 261
2129
2130 -- data Clause = ...
2131 clauseIdKey :: Unique
2132 clauseIdKey         = mkPreludeMiscIdUnique 262
2133
2134
2135 -- data Exp = ...
2136 varEIdKey, conEIdKey, litEIdKey, appEIdKey, infixEIdKey, infixAppIdKey,
2137     sectionLIdKey, sectionRIdKey, lamEIdKey, tupEIdKey, unboxedTupEIdKey,
2138     condEIdKey,
2139     letEIdKey, caseEIdKey, doEIdKey, compEIdKey,
2140     fromEIdKey, fromThenEIdKey, fromToEIdKey, fromThenToEIdKey,
2141     listEIdKey, sigEIdKey, recConEIdKey, recUpdEIdKey :: Unique
2142 varEIdKey         = mkPreludeMiscIdUnique 270
2143 conEIdKey         = mkPreludeMiscIdUnique 271
2144 litEIdKey         = mkPreludeMiscIdUnique 272
2145 appEIdKey         = mkPreludeMiscIdUnique 273
2146 infixEIdKey       = mkPreludeMiscIdUnique 274
2147 infixAppIdKey     = mkPreludeMiscIdUnique 275
2148 sectionLIdKey     = mkPreludeMiscIdUnique 276
2149 sectionRIdKey     = mkPreludeMiscIdUnique 277
2150 lamEIdKey         = mkPreludeMiscIdUnique 278
2151 tupEIdKey         = mkPreludeMiscIdUnique 279
2152 unboxedTupEIdKey  = mkPreludeMiscIdUnique 280
2153 condEIdKey        = mkPreludeMiscIdUnique 281
2154 letEIdKey         = mkPreludeMiscIdUnique 282
2155 caseEIdKey        = mkPreludeMiscIdUnique 283
2156 doEIdKey          = mkPreludeMiscIdUnique 284
2157 compEIdKey        = mkPreludeMiscIdUnique 285
2158 fromEIdKey        = mkPreludeMiscIdUnique 286
2159 fromThenEIdKey    = mkPreludeMiscIdUnique 287
2160 fromToEIdKey      = mkPreludeMiscIdUnique 288
2161 fromThenToEIdKey  = mkPreludeMiscIdUnique 289
2162 listEIdKey        = mkPreludeMiscIdUnique 290
2163 sigEIdKey         = mkPreludeMiscIdUnique 291
2164 recConEIdKey      = mkPreludeMiscIdUnique 292
2165 recUpdEIdKey      = mkPreludeMiscIdUnique 293
2166
2167 -- type FieldExp = ...
2168 fieldExpIdKey :: Unique
2169 fieldExpIdKey       = mkPreludeMiscIdUnique 310
2170
2171 -- data Body = ...
2172 guardedBIdKey, normalBIdKey :: Unique
2173 guardedBIdKey     = mkPreludeMiscIdUnique 311
2174 normalBIdKey      = mkPreludeMiscIdUnique 312
2175
2176 -- data Guard = ...
2177 normalGEIdKey, patGEIdKey :: Unique
2178 normalGEIdKey     = mkPreludeMiscIdUnique 313
2179 patGEIdKey        = mkPreludeMiscIdUnique 314
2180
2181 -- data Stmt = ...
2182 bindSIdKey, letSIdKey, noBindSIdKey, parSIdKey :: Unique
2183 bindSIdKey       = mkPreludeMiscIdUnique 320
2184 letSIdKey        = mkPreludeMiscIdUnique 321
2185 noBindSIdKey     = mkPreludeMiscIdUnique 322
2186 parSIdKey        = mkPreludeMiscIdUnique 323
2187
2188 -- data Dec = ...
2189 funDIdKey, valDIdKey, dataDIdKey, newtypeDIdKey, tySynDIdKey,
2190     classDIdKey, instanceDIdKey, sigDIdKey, forImpDIdKey, pragInlDIdKey,
2191     pragSpecDIdKey, pragSpecInlDIdKey, familyNoKindDIdKey, familyKindDIdKey,
2192     dataInstDIdKey, newtypeInstDIdKey, tySynInstDIdKey :: Unique 
2193 funDIdKey          = mkPreludeMiscIdUnique 330
2194 valDIdKey          = mkPreludeMiscIdUnique 331
2195 dataDIdKey         = mkPreludeMiscIdUnique 332
2196 newtypeDIdKey      = mkPreludeMiscIdUnique 333
2197 tySynDIdKey        = mkPreludeMiscIdUnique 334
2198 classDIdKey        = mkPreludeMiscIdUnique 335
2199 instanceDIdKey     = mkPreludeMiscIdUnique 336
2200 sigDIdKey          = mkPreludeMiscIdUnique 337
2201 forImpDIdKey       = mkPreludeMiscIdUnique 338
2202 pragInlDIdKey      = mkPreludeMiscIdUnique 339
2203 pragSpecDIdKey     = mkPreludeMiscIdUnique 340
2204 pragSpecInlDIdKey  = mkPreludeMiscIdUnique 341
2205 familyNoKindDIdKey = mkPreludeMiscIdUnique 342
2206 familyKindDIdKey   = mkPreludeMiscIdUnique 343
2207 dataInstDIdKey     = mkPreludeMiscIdUnique 344
2208 newtypeInstDIdKey  = mkPreludeMiscIdUnique 345
2209 tySynInstDIdKey    = mkPreludeMiscIdUnique 346
2210
2211 -- type Cxt = ...
2212 cxtIdKey :: Unique
2213 cxtIdKey            = mkPreludeMiscIdUnique 360
2214
2215 -- data Pred = ...
2216 classPIdKey, equalPIdKey :: Unique
2217 classPIdKey         = mkPreludeMiscIdUnique 361
2218 equalPIdKey         = mkPreludeMiscIdUnique 362
2219
2220 -- data Strict = ...
2221 isStrictKey, notStrictKey :: Unique
2222 isStrictKey         = mkPreludeMiscIdUnique 363
2223 notStrictKey        = mkPreludeMiscIdUnique 364
2224
2225 -- data Con = ...
2226 normalCIdKey, recCIdKey, infixCIdKey, forallCIdKey :: Unique
2227 normalCIdKey      = mkPreludeMiscIdUnique 370
2228 recCIdKey         = mkPreludeMiscIdUnique 371
2229 infixCIdKey       = mkPreludeMiscIdUnique 372
2230 forallCIdKey      = mkPreludeMiscIdUnique 373
2231
2232 -- type StrictType = ...
2233 strictTKey :: Unique
2234 strictTKey        = mkPreludeMiscIdUnique 374
2235
2236 -- type VarStrictType = ...
2237 varStrictTKey :: Unique
2238 varStrictTKey     = mkPreludeMiscIdUnique 375
2239
2240 -- data Type = ...
2241 forallTIdKey, varTIdKey, conTIdKey, tupleTIdKey, unboxedTupleTIdKey, arrowTIdKey,
2242     listTIdKey, appTIdKey, sigTIdKey :: Unique
2243 forallTIdKey       = mkPreludeMiscIdUnique 380
2244 varTIdKey          = mkPreludeMiscIdUnique 381
2245 conTIdKey          = mkPreludeMiscIdUnique 382
2246 tupleTIdKey        = mkPreludeMiscIdUnique 383
2247 unboxedTupleTIdKey = mkPreludeMiscIdUnique 384
2248 arrowTIdKey        = mkPreludeMiscIdUnique 385
2249 listTIdKey         = mkPreludeMiscIdUnique 386
2250 appTIdKey          = mkPreludeMiscIdUnique 387
2251 sigTIdKey          = mkPreludeMiscIdUnique 388
2252
2253 -- data TyVarBndr = ...
2254 plainTVIdKey, kindedTVIdKey :: Unique
2255 plainTVIdKey      = mkPreludeMiscIdUnique 390
2256 kindedTVIdKey     = mkPreludeMiscIdUnique 391
2257
2258 -- data Kind = ...
2259 starKIdKey, arrowKIdKey :: Unique
2260 starKIdKey        = mkPreludeMiscIdUnique 392
2261 arrowKIdKey       = mkPreludeMiscIdUnique 393
2262
2263 -- data Callconv = ...
2264 cCallIdKey, stdCallIdKey :: Unique
2265 cCallIdKey      = mkPreludeMiscIdUnique 394
2266 stdCallIdKey    = mkPreludeMiscIdUnique 395
2267
2268 -- data Safety = ...
2269 unsafeIdKey, safeIdKey, threadsafeIdKey, interruptibleIdKey :: Unique
2270 unsafeIdKey        = mkPreludeMiscIdUnique 400
2271 safeIdKey          = mkPreludeMiscIdUnique 401
2272 threadsafeIdKey    = mkPreludeMiscIdUnique 402
2273 interruptibleIdKey = mkPreludeMiscIdUnique 403
2274
2275 -- data InlineSpec =
2276 inlineSpecNoPhaseIdKey, inlineSpecPhaseIdKey :: Unique
2277 inlineSpecNoPhaseIdKey = mkPreludeMiscIdUnique 404
2278 inlineSpecPhaseIdKey   = mkPreludeMiscIdUnique 405
2279
2280 -- data FunDep = ...
2281 funDepIdKey :: Unique
2282 funDepIdKey = mkPreludeMiscIdUnique 406
2283
2284 -- data FamFlavour = ...
2285 typeFamIdKey, dataFamIdKey :: Unique
2286 typeFamIdKey = mkPreludeMiscIdUnique 407
2287 dataFamIdKey = mkPreludeMiscIdUnique 408
2288
2289 -- quasiquoting
2290 quoteExpKey, quotePatKey, quoteDecKey, quoteTypeKey :: Unique
2291 quoteExpKey  = mkPreludeMiscIdUnique 410
2292 quotePatKey  = mkPreludeMiscIdUnique 411
2293 quoteDecKey  = mkPreludeMiscIdUnique 412
2294 quoteTypeKey = mkPreludeMiscIdUnique 413