1 -----------------------------------------------------------------------------
2 -- The purpose of this module is to transform an HsExpr into a CoreExpr which
3 -- when evaluated, returns a (Meta.Q Meta.Exp) computation analogous to the
4 -- input HsExpr. We do this in the DsM monad, which supplies access to
5 -- CoreExpr's of the "smart constructors" of the Meta.Exp datatype.
7 -- It also defines a bunch of knownKeyNames, in the same way as is done
8 -- in prelude/PrelNames. It's much more convenient to do it here, becuase
9 -- otherwise we have to recompile PrelNames whenever we add a Name, which is
10 -- a Royal Pain (triggers other recompilation).
11 -----------------------------------------------------------------------------
14 module DsMeta( dsBracket,
15 templateHaskellNames, qTyConName, nameTyConName,
16 liftName, expQTyConName, decQTyConName, typeQTyConName,
17 decTyConName, typeTyConName, mkNameG_dName, mkNameG_vName, mkNameG_tcName
20 #include "HsVersions.h"
22 import {-# SOURCE #-} DsExpr ( dsExpr )
24 import MatchLit ( dsLit )
25 import DsUtils ( mkListExpr, mkStringLit, mkCoreTup, mkIntExpr )
28 import qualified Language.Haskell.TH as TH
31 import PrelNames ( rationalTyConName, integerTyConName, negateName )
32 import OccName ( isDataOcc, isTvOcc, occNameUserString )
33 -- To avoid clashes with DsMeta.varName we must make a local alias for OccName.varName
34 -- we do this by removing varName from the import of OccName above, making
35 -- a qualified instance of OccName and using OccNameAlias.varName where varName
36 -- ws previously used in this file.
37 import qualified OccName
39 import Module ( Module, mkModule, mkModuleName, moduleUserString )
40 import Id ( Id, mkLocalId )
41 import OccName ( mkOccFS )
42 import Name ( Name, mkExternalName, localiseName, nameOccName, nameModule,
43 isExternalName, getSrcLoc )
45 import Type ( Type, mkGenTyConApp )
46 import TcType ( tcTyConAppArgs )
47 import TyCon ( tyConName )
48 import TysWiredIn ( parrTyCon )
50 import CoreUtils ( exprType )
51 import SrcLoc ( noSrcLoc, unLoc, Located(..), SrcSpan, srcLocSpan )
52 import Maybe ( catMaybes )
53 import Unique ( mkPreludeTyConUnique, mkPreludeMiscIdUnique, getKey, Uniquable(..) )
54 import BasicTypes ( NewOrData(..), isBoxed )
55 import Packages ( thPackage )
57 import Bag ( bagToList )
59 import Monad ( zipWithM )
60 import List ( sortBy )
62 -----------------------------------------------------------------------------
63 dsBracket :: HsBracket Name -> [PendingSplice] -> DsM CoreExpr
64 -- Returns a CoreExpr of type TH.ExpQ
65 -- The quoted thing is parameterised over Name, even though it has
66 -- been type checked. We don't want all those type decorations!
68 dsBracket brack splices
69 = dsExtendMetaEnv new_bit (do_brack brack)
71 new_bit = mkNameEnv [(n, Splice (unLoc e)) | (n,e) <- splices]
73 do_brack (VarBr n) = do { MkC e1 <- lookupOcc n ; return e1 }
74 do_brack (ExpBr e) = do { MkC e1 <- repLE e ; return e1 }
75 do_brack (PatBr p) = do { MkC p1 <- repLP p ; return p1 }
76 do_brack (TypBr t) = do { MkC t1 <- repLTy t ; return t1 }
77 do_brack (DecBr ds) = do { MkC ds1 <- repTopDs ds ; return ds1 }
79 {- -------------- Examples --------------------
83 gensym (unpackString "x"#) `bindQ` \ x1::String ->
84 lam (pvar x1) (var x1)
87 [| \x -> $(f [| x |]) |]
89 gensym (unpackString "x"#) `bindQ` \ x1::String ->
90 lam (pvar x1) (f (var x1))
94 -------------------------------------------------------
96 -------------------------------------------------------
98 repTopDs :: HsGroup Name -> DsM (Core (TH.Q [TH.Dec]))
100 = do { let { bndrs = map unLoc (groupBinders group) } ;
101 ss <- mkGenSyms bndrs ;
103 -- Bind all the names mainly to avoid repeated use of explicit strings.
105 -- do { t :: String <- genSym "T" ;
106 -- return (Data t [] ...more t's... }
107 -- The other important reason is that the output must mention
108 -- only "T", not "Foo:T" where Foo is the current module
111 decls <- addBinds ss (do {
112 val_ds <- mapM rep_bind_group (hs_valds group) ;
113 tycl_ds <- mapM repTyClD (hs_tyclds group) ;
114 inst_ds <- mapM repInstD' (hs_instds group) ;
116 return (de_loc $ sort_by_loc $ concat val_ds ++ catMaybes tycl_ds ++ inst_ds) }) ;
118 decl_ty <- lookupType decQTyConName ;
119 let { core_list = coreList' decl_ty decls } ;
121 dec_ty <- lookupType decTyConName ;
122 q_decs <- repSequenceQ dec_ty core_list ;
124 wrapNongenSyms ss q_decs
125 -- Do *not* gensym top-level binders
128 groupBinders (HsGroup { hs_valds = val_decls, hs_tyclds = tycl_decls,
129 hs_fords = foreign_decls })
130 -- Collect the binders of a Group
131 = collectGroupBinders val_decls ++
132 [n | d <- tycl_decls, n <- tyClDeclNames (unLoc d)] ++
133 [n | L _ (ForeignImport n _ _ _) <- foreign_decls]
136 {- Note [Binders and occurrences]
137 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
138 When we desugar [d| data T = MkT |]
140 Data "T" [] [Con "MkT" []] []
142 Data "Foo:T" [] [Con "Foo:MkT" []] []
143 That is, the new data decl should fit into whatever new module it is
144 asked to fit in. We do *not* clone, though; no need for this:
151 then we must desugar to
152 foo = Data "Foo:T" [] [Con "Foo:MkT" []] []
154 So in repTopDs we bring the binders into scope with mkGenSyms and addBinds.
155 And we use lookupOcc, rather than lookupBinder
156 in repTyClD and repC.
160 repTyClD :: LTyClDecl Name -> DsM (Maybe (SrcSpan, Core TH.DecQ))
162 repTyClD (L loc (TyData { tcdND = DataType, tcdCtxt = cxt,
163 tcdLName = tc, tcdTyVars = tvs,
164 tcdCons = cons, tcdDerivs = mb_derivs }))
165 = do { tc1 <- lookupLOcc tc ; -- See note [Binders and occurrences]
166 dec <- addTyVarBinds tvs $ \bndrs -> do {
167 cxt1 <- repLContext cxt ;
168 cons1 <- mapM repC cons ;
169 cons2 <- coreList conQTyConName cons1 ;
170 derivs1 <- repDerivs mb_derivs ;
171 bndrs1 <- coreList nameTyConName bndrs ;
172 repData cxt1 tc1 bndrs1 cons2 derivs1 } ;
173 return $ Just (loc, dec) }
175 repTyClD (L loc (TyData { tcdND = NewType, tcdCtxt = cxt,
176 tcdLName = tc, tcdTyVars = tvs,
177 tcdCons = [con], tcdDerivs = mb_derivs }))
178 = do { tc1 <- lookupLOcc tc ; -- See note [Binders and occurrences]
179 dec <- addTyVarBinds tvs $ \bndrs -> do {
180 cxt1 <- repLContext cxt ;
182 derivs1 <- repDerivs mb_derivs ;
183 bndrs1 <- coreList nameTyConName bndrs ;
184 repNewtype cxt1 tc1 bndrs1 con1 derivs1 } ;
185 return $ Just (loc, dec) }
187 repTyClD (L loc (TySynonym { tcdLName = tc, tcdTyVars = tvs, tcdSynRhs = ty }))
188 = do { tc1 <- lookupLOcc tc ; -- See note [Binders and occurrences]
189 dec <- addTyVarBinds tvs $ \bndrs -> do {
191 bndrs1 <- coreList nameTyConName bndrs ;
192 repTySyn tc1 bndrs1 ty1 } ;
193 return (Just (loc, dec)) }
195 repTyClD (L loc (ClassDecl { tcdCtxt = cxt, tcdLName = cls,
197 tcdFDs = [], -- We don't understand functional dependencies
198 tcdSigs = sigs, tcdMeths = meth_binds }))
199 = do { cls1 <- lookupLOcc cls ; -- See note [Binders and occurrences]
200 dec <- addTyVarBinds tvs $ \bndrs -> do {
201 cxt1 <- repLContext cxt ;
202 sigs1 <- rep_sigs sigs ;
203 binds1 <- rep_binds meth_binds ;
204 decls1 <- coreList decQTyConName (sigs1 ++ binds1) ;
205 bndrs1 <- coreList nameTyConName bndrs ;
206 repClass cxt1 cls1 bndrs1 decls1 } ;
207 return $ Just (loc, dec) }
210 repTyClD (L loc d) = do { dsWarn (loc, hang msg 4 (ppr d)) ;
214 msg = ptext SLIT("Cannot desugar this Template Haskell declaration:")
216 repInstD' (L loc (InstDecl ty binds _))
217 -- Ignore user pragmas for now
218 = do { cxt1 <- repContext cxt
219 ; inst_ty1 <- repPred (HsClassP cls tys)
220 ; ss <- mkGenSyms (collectHsBindBinders binds)
221 ; binds1 <- addBinds ss (rep_binds binds)
222 ; decls1 <- coreList decQTyConName binds1
223 ; decls2 <- wrapNongenSyms ss decls1
224 -- wrapNonGenSyms: do not clone the class op names!
225 -- They must be called 'op' etc, not 'op34'
226 ; i <- repInst cxt1 inst_ty1 decls2
229 (_, cxt, cls, tys) = splitHsInstDeclTy (unLoc ty)
231 -------------------------------------------------------
233 -------------------------------------------------------
235 repC :: LConDecl Name -> DsM (Core TH.ConQ)
236 repC (L loc (ConDecl con [] (L _ []) details))
237 = do { con1 <- lookupLOcc con ; -- See note [Binders and occurrences]
238 repConstr con1 details }
240 repBangTy :: LBangType Name -> DsM (Core (TH.StrictTypeQ))
241 repBangTy (L _ (BangType str ty)) = do
242 MkC s <- rep2 strName []
244 rep2 strictTypeName [s, t]
245 where strName = case str of
246 HsNoBang -> notStrictName
247 other -> isStrictName
249 -------------------------------------------------------
251 -------------------------------------------------------
253 repDerivs :: Maybe (LHsContext Name) -> DsM (Core [TH.Name])
254 repDerivs Nothing = coreList nameTyConName []
255 repDerivs (Just (L _ ctxt))
256 = do { strs <- mapM rep_deriv ctxt ;
257 coreList nameTyConName strs }
259 rep_deriv :: LHsPred Name -> DsM (Core TH.Name)
260 -- Deriving clauses must have the simple H98 form
261 rep_deriv (L _ (HsClassP cls [])) = lookupOcc cls
262 rep_deriv other = panic "rep_deriv"
265 -------------------------------------------------------
266 -- Signatures in a class decl, or a group of bindings
267 -------------------------------------------------------
269 rep_sigs :: [LSig Name] -> DsM [Core TH.DecQ]
270 rep_sigs sigs = do locs_cores <- rep_sigs' sigs
271 return $ de_loc $ sort_by_loc locs_cores
273 rep_sigs' :: [LSig Name] -> DsM [(SrcSpan, Core TH.DecQ)]
274 -- We silently ignore ones we don't recognise
275 rep_sigs' sigs = do { sigs1 <- mapM rep_sig sigs ;
276 return (concat sigs1) }
278 rep_sig :: LSig Name -> DsM [(SrcSpan, Core TH.DecQ)]
280 -- Empty => Too hard, signature ignored
281 rep_sig (L loc (Sig nm ty)) = rep_proto nm ty loc
282 rep_sig other = return []
284 rep_proto :: Located Name -> LHsType Name -> SrcSpan -> DsM [(SrcSpan, Core TH.DecQ)]
285 rep_proto nm ty loc = do { nm1 <- lookupLOcc nm ;
287 sig <- repProto nm1 ty1 ;
288 return [(loc, sig)] }
291 -------------------------------------------------------
293 -------------------------------------------------------
295 -- gensym a list of type variables and enter them into the meta environment;
296 -- the computations passed as the second argument is executed in that extended
297 -- meta environment and gets the *new* names on Core-level as an argument
299 addTyVarBinds :: [LHsTyVarBndr Name] -- the binders to be added
300 -> ([Core TH.Name] -> DsM (Core (TH.Q a))) -- action in the ext env
301 -> DsM (Core (TH.Q a))
302 addTyVarBinds tvs m =
304 let names = map (hsTyVarName.unLoc) tvs
305 freshNames <- mkGenSyms names
306 term <- addBinds freshNames $ do
307 bndrs <- mapM lookupBinder names
309 wrapGenSyns freshNames term
311 -- represent a type context
313 repLContext :: LHsContext Name -> DsM (Core TH.CxtQ)
314 repLContext (L _ ctxt) = repContext ctxt
316 repContext :: HsContext Name -> DsM (Core TH.CxtQ)
318 preds <- mapM repLPred ctxt
319 predList <- coreList typeQTyConName preds
322 -- represent a type predicate
324 repLPred :: LHsPred Name -> DsM (Core TH.TypeQ)
325 repLPred (L _ p) = repPred p
327 repPred :: HsPred Name -> DsM (Core TH.TypeQ)
328 repPred (HsClassP cls tys) = do
329 tcon <- repTy (HsTyVar cls)
332 repPred (HsIParam _ _) =
333 panic "DsMeta.repTy: Can't represent predicates with implicit parameters"
335 -- yield the representation of a list of types
337 repLTys :: [LHsType Name] -> DsM [Core TH.TypeQ]
338 repLTys tys = mapM repLTy tys
342 repLTy :: LHsType Name -> DsM (Core TH.TypeQ)
343 repLTy (L _ ty) = repTy ty
345 repTy :: HsType Name -> DsM (Core TH.TypeQ)
346 repTy (HsForAllTy _ tvs ctxt ty) =
347 addTyVarBinds tvs $ \bndrs -> do
348 ctxt1 <- repLContext ctxt
350 bndrs1 <- coreList nameTyConName bndrs
351 repTForall bndrs1 ctxt1 ty1
354 | isTvOcc (nameOccName n) = do
355 tv1 <- lookupBinder n
360 repTy (HsAppTy f a) = do
364 repTy (HsFunTy f a) = do
367 tcon <- repArrowTyCon
368 repTapps tcon [f1, a1]
369 repTy (HsListTy t) = do
373 repTy (HsPArrTy t) = do
375 tcon <- repTy (HsTyVar (tyConName parrTyCon))
377 repTy (HsTupleTy tc tys) = do
379 tcon <- repTupleTyCon (length tys)
381 repTy (HsOpTy ty1 n ty2) = repLTy ((nlHsTyVar (unLoc n) `nlHsAppTy` ty1)
383 repTy (HsParTy t) = repLTy t
385 panic "DsMeta.repTy: Can't represent number types (for generics)"
386 repTy (HsPredTy pred) = repLPred pred
387 repTy (HsKindSig ty kind) =
388 panic "DsMeta.repTy: Can't represent explicit kind signatures yet"
391 -----------------------------------------------------------------------------
393 -----------------------------------------------------------------------------
395 repLEs :: [LHsExpr Name] -> DsM (Core [TH.ExpQ])
396 repLEs es = do { es' <- mapM repLE es ;
397 coreList expQTyConName es' }
399 -- FIXME: some of these panics should be converted into proper error messages
400 -- unless we can make sure that constructs, which are plainly not
401 -- supported in TH already lead to error messages at an earlier stage
402 repLE :: LHsExpr Name -> DsM (Core TH.ExpQ)
403 repLE (L _ e) = repE e
405 repE :: HsExpr Name -> DsM (Core TH.ExpQ)
407 do { mb_val <- dsLookupMetaEnv x
409 Nothing -> do { str <- globalVar x
410 ; repVarOrCon x str }
411 Just (Bound y) -> repVarOrCon x (coreVar y)
412 Just (Splice e) -> do { e' <- dsExpr e
413 ; return (MkC e') } }
414 repE (HsIPVar x) = panic "DsMeta.repE: Can't represent implicit parameters"
416 -- Remember, we're desugaring renamer output here, so
417 -- HsOverlit can definitely occur
418 repE (HsOverLit l) = do { a <- repOverloadedLiteral l; repLit a }
419 repE (HsLit l) = do { a <- repLiteral l; repLit a }
420 repE (HsLam m) = repLambda m
421 repE (HsApp x y) = do {a <- repLE x; b <- repLE y; repApp a b}
423 repE (OpApp e1 op fix e2) =
424 do { arg1 <- repLE e1;
427 repInfixApp arg1 the_op arg2 }
428 repE (NegApp x nm) = do
430 negateVar <- lookupOcc negateName >>= repVar
432 repE (HsPar x) = repLE x
433 repE (SectionL x y) = do { a <- repLE x; b <- repLE y; repSectionL a b }
434 repE (SectionR x y) = do { a <- repLE x; b <- repLE y; repSectionR a b }
435 repE (HsCase e ms) = do { arg <- repLE e
436 ; ms2 <- mapM repMatchTup ms
437 ; repCaseE arg (nonEmptyCoreList ms2) }
438 repE (HsIf x y z) = do
443 repE (HsLet bs e) = do { (ss,ds) <- repBinds bs
444 ; e2 <- addBinds ss (repLE e)
447 -- FIXME: I haven't got the types here right yet
448 repE (HsDo DoExpr sts _ ty)
449 = do { (ss,zs) <- repLSts sts;
450 e <- repDoE (nonEmptyCoreList zs);
452 repE (HsDo ListComp sts _ ty)
453 = do { (ss,zs) <- repLSts sts;
454 e <- repComp (nonEmptyCoreList zs);
456 repE (HsDo _ _ _ _) = panic "DsMeta.repE: Can't represent mdo and [: :] yet"
457 repE (ExplicitList ty es) = do { xs <- repLEs es; repListExp xs }
458 repE (ExplicitPArr ty es) =
459 panic "DsMeta.repE: No explicit parallel arrays yet"
460 repE (ExplicitTuple es boxed)
461 | isBoxed boxed = do { xs <- repLEs es; repTup xs }
462 | otherwise = panic "DsMeta.repE: Can't represent unboxed tuples"
463 repE (RecordCon c flds)
464 = do { x <- lookupLOcc c;
465 fs <- repFields flds;
467 repE (RecordUpd e flds)
469 fs <- repFields flds;
472 repE (ExprWithTySig e ty) = do { e1 <- repLE e; t1 <- repLTy ty; repSigExp e1 t1 }
473 repE (ArithSeqIn aseq) =
475 From e -> do { ds1 <- repLE e; repFrom ds1 }
484 FromThenTo e1 e2 e3 -> do
488 repFromThenTo ds1 ds2 ds3
489 repE (PArrSeqOut _ aseq) = panic "DsMeta.repE: parallel array seq.s missing"
490 repE (HsCoreAnn _ _) = panic "DsMeta.repE: Can't represent CoreAnn" -- hdaume: core annotations
491 repE (HsSCC _ _) = panic "DsMeta.repE: Can't represent SCC"
492 repE (HsBracketOut _ _) =
493 panic "DsMeta.repE: Can't represent Oxford brackets"
494 repE (HsSplice n e) = do { mb_val <- dsLookupMetaEnv n
496 Just (Splice e) -> do { e' <- dsExpr e
498 other -> pprPanic "HsSplice" (ppr n) }
500 pprPanic "DsMeta.repE: Illegal expression form" (ppr e)
502 -----------------------------------------------------------------------------
503 -- Building representations of auxillary structures like Match, Clause, Stmt,
505 repMatchTup :: LMatch Name -> DsM (Core TH.MatchQ)
506 repMatchTup (L _ (Match [p] ty (GRHSs guards wheres ty2))) =
507 do { ss1 <- mkGenSyms (collectPatBinders p)
508 ; addBinds ss1 $ do {
510 ; (ss2,ds) <- repBinds wheres
511 ; addBinds ss2 $ do {
512 ; gs <- repGuards guards
513 ; match <- repMatch p1 gs ds
514 ; wrapGenSyns (ss1++ss2) match }}}
516 repClauseTup :: LMatch Name -> DsM (Core TH.ClauseQ)
517 repClauseTup (L _ (Match ps ty (GRHSs guards wheres ty2))) =
518 do { ss1 <- mkGenSyms (collectPatsBinders ps)
519 ; addBinds ss1 $ do {
521 ; (ss2,ds) <- repBinds wheres
522 ; addBinds ss2 $ do {
523 gs <- repGuards guards
524 ; clause <- repClause ps1 gs ds
525 ; wrapGenSyns (ss1++ss2) clause }}}
527 repGuards :: [LGRHS Name] -> DsM (Core TH.BodyQ)
528 repGuards [L _ (GRHS [L _ (ResultStmt e)])]
529 = do {a <- repLE e; repNormal a }
531 = do { zs <- mapM process other;
532 repGuarded (nonEmptyCoreList (map corePair zs)) }
534 process (L _ (GRHS [L _ (ExprStmt e1 ty),
535 L _ (ResultStmt e2)]))
536 = do { x <- repLE e1; y <- repLE e2; return (x, y) }
537 process other = panic "Non Haskell 98 guarded body"
539 repFields :: [(Located Name, LHsExpr Name)] -> DsM (Core [TH.FieldExp])
541 fnames <- mapM lookupLOcc (map fst flds)
542 es <- mapM repLE (map snd flds)
543 fs <- zipWithM (\n x -> rep2 fieldExpName [unC n, unC x]) fnames es
544 coreList fieldExpTyConName fs
547 -----------------------------------------------------------------------------
548 -- Representing Stmt's is tricky, especially if bound variables
549 -- shadow each other. Consider: [| do { x <- f 1; x <- f x; g x } |]
550 -- First gensym new names for every variable in any of the patterns.
551 -- both static (x'1 and x'2), and dynamic ((gensym "x") and (gensym "y"))
552 -- if variables didn't shaddow, the static gensym wouldn't be necessary
553 -- and we could reuse the original names (x and x).
555 -- do { x'1 <- gensym "x"
556 -- ; x'2 <- gensym "x"
557 -- ; doE [ BindSt (pvar x'1) [| f 1 |]
558 -- , BindSt (pvar x'2) [| f x |]
559 -- , NoBindSt [| g x |]
563 -- The strategy is to translate a whole list of do-bindings by building a
564 -- bigger environment, and a bigger set of meta bindings
565 -- (like: x'1 <- gensym "x" ) and then combining these with the translations
566 -- of the expressions within the Do
568 -----------------------------------------------------------------------------
569 -- The helper function repSts computes the translation of each sub expression
570 -- and a bunch of prefix bindings denoting the dynamic renaming.
572 repLSts :: [LStmt Name] -> DsM ([GenSymBind], [Core TH.StmtQ])
573 repLSts stmts = repSts (map unLoc stmts)
575 repSts :: [Stmt Name] -> DsM ([GenSymBind], [Core TH.StmtQ])
576 repSts [ResultStmt e] =
578 ; e1 <- repNoBindSt a
579 ; return ([], [e1]) }
580 repSts (BindStmt p e : ss) =
582 ; ss1 <- mkGenSyms (collectPatBinders p)
583 ; addBinds ss1 $ do {
585 ; (ss2,zs) <- repSts ss
586 ; z <- repBindSt p1 e2
587 ; return (ss1++ss2, z : zs) }}
588 repSts (LetStmt bs : ss) =
589 do { (ss1,ds) <- repBinds bs
591 ; (ss2,zs) <- addBinds ss1 (repSts ss)
592 ; return (ss1++ss2, z : zs) }
593 repSts (ExprStmt e ty : ss) =
595 ; z <- repNoBindSt e2
596 ; (ss2,zs) <- repSts ss
597 ; return (ss2, z : zs) }
598 repSts other = panic "Exotic Stmt in meta brackets"
601 -----------------------------------------------------------
603 -----------------------------------------------------------
605 repBinds :: [HsBindGroup Name] -> DsM ([GenSymBind], Core [TH.DecQ])
607 = do { let { bndrs = map unLoc (collectGroupBinders decs) }
608 -- No need to worrry about detailed scopes within
609 -- the binding group, because we are talking Names
610 -- here, so we can safely treat it as a mutually
612 ; ss <- mkGenSyms bndrs
613 ; core <- addBinds ss (rep_bind_groups decs)
614 ; core_list <- coreList decQTyConName core
615 ; return (ss, core_list) }
617 rep_bind_groups :: [HsBindGroup Name] -> DsM [Core TH.DecQ]
618 -- Assumes: all the binders of the binding are alrady in the meta-env
619 rep_bind_groups binds = do
620 locs_cores_s <- mapM rep_bind_group binds
621 return $ de_loc $ sort_by_loc (concat locs_cores_s)
623 rep_bind_group :: HsBindGroup Name -> DsM [(SrcSpan, Core TH.DecQ)]
624 -- Assumes: all the binders of the binding are alrady in the meta-env
625 rep_bind_group (HsBindGroup bs sigs _)
626 = do { core1 <- mapM rep_bind (bagToList bs)
627 ; core2 <- rep_sigs' sigs
628 ; return (core1 ++ core2) }
629 rep_bind_group (HsIPBinds _)
630 = panic "DsMeta:repBinds: can't do implicit parameters"
632 rep_binds :: LHsBinds Name -> DsM [Core TH.DecQ]
633 -- Assumes: all the binders of the binding are alrady in the meta-env
635 locs_cores <- mapM rep_bind (bagToList binds)
636 return $ de_loc $ sort_by_loc locs_cores
638 rep_bind :: LHsBind Name -> DsM (SrcSpan, Core TH.DecQ)
639 -- Assumes: all the binders of the binding are alrady in the meta-env
641 -- Note GHC treats declarations of a variable (not a pattern)
642 -- e.g. x = g 5 as a Fun MonoBinds. This is indicated by a single match
643 -- with an empty list of patterns
644 rep_bind (L loc (FunBind fn infx [L _ (Match [] ty (GRHSs guards wheres ty2))]))
645 = do { (ss,wherecore) <- repBinds wheres
646 ; guardcore <- addBinds ss (repGuards guards)
647 ; fn' <- lookupLBinder fn
649 ; ans <- repVal p guardcore wherecore
650 ; return (loc, ans) }
652 rep_bind (L loc (FunBind fn infx ms))
653 = do { ms1 <- mapM repClauseTup ms
654 ; fn' <- lookupLBinder fn
655 ; ans <- repFun fn' (nonEmptyCoreList ms1)
656 ; return (loc, ans) }
658 rep_bind (L loc (PatBind pat (GRHSs guards wheres ty2)))
659 = do { patcore <- repLP pat
660 ; (ss,wherecore) <- repBinds wheres
661 ; guardcore <- addBinds ss (repGuards guards)
662 ; ans <- repVal patcore guardcore wherecore
663 ; return (loc, ans) }
665 rep_bind (L loc (VarBind v e))
666 = do { v' <- lookupBinder v
669 ; patcore <- repPvar v'
670 ; empty_decls <- coreList decQTyConName []
671 ; ans <- repVal patcore x empty_decls
672 ; return (srcLocSpan (getSrcLoc v), ans) }
674 -----------------------------------------------------------------------------
675 -- Since everything in a Bind is mutually recursive we need rename all
676 -- all the variables simultaneously. For example:
677 -- [| AndMonoBinds (f x = x + g 2) (g x = f 1 + 2) |] would translate to
678 -- do { f'1 <- gensym "f"
679 -- ; g'2 <- gensym "g"
680 -- ; [ do { x'3 <- gensym "x"; fun f'1 [pvar x'3] [| x + g2 |]},
681 -- do { x'4 <- gensym "x"; fun g'2 [pvar x'4] [| f 1 + 2 |]}
683 -- This requires collecting the bindings (f'1 <- gensym "f"), and the
684 -- environment ( f |-> f'1 ) from each binding, and then unioning them
685 -- together. As we do this we collect GenSymBinds's which represent the renamed
686 -- variables bound by the Bindings. In order not to lose track of these
687 -- representations we build a shadow datatype MB with the same structure as
688 -- MonoBinds, but which has slots for the representations
691 -----------------------------------------------------------------------------
692 -- GHC allows a more general form of lambda abstraction than specified
693 -- by Haskell 98. In particular it allows guarded lambda's like :
694 -- (\ x | even x -> 0 | odd x -> 1) at the moment we can't represent this in
695 -- Haskell Template's Meta.Exp type so we punt if it isn't a simple thing like
696 -- (\ p1 .. pn -> exp) by causing an error.
698 repLambda :: LMatch Name -> DsM (Core TH.ExpQ)
699 repLambda (L _ (Match ps _ (GRHSs [L _ (GRHS [L _ (ResultStmt e)])] [] _)))
700 = do { let bndrs = collectPatsBinders ps ;
701 ; ss <- mkGenSyms bndrs
702 ; lam <- addBinds ss (
703 do { xs <- repLPs ps; body <- repLE e; repLam xs body })
704 ; wrapGenSyns ss lam }
706 repLambda z = panic "Can't represent a guarded lambda in Template Haskell"
709 -----------------------------------------------------------------------------
711 -- repP deals with patterns. It assumes that we have already
712 -- walked over the pattern(s) once to collect the binders, and
713 -- have extended the environment. So every pattern-bound
714 -- variable should already appear in the environment.
716 -- Process a list of patterns
717 repLPs :: [LPat Name] -> DsM (Core [TH.Pat])
718 repLPs ps = do { ps' <- mapM repLP ps ;
719 coreList patTyConName ps' }
721 repLP :: LPat Name -> DsM (Core TH.Pat)
722 repLP (L _ p) = repP p
724 repP :: Pat Name -> DsM (Core TH.Pat)
725 repP (WildPat _) = repPwild
726 repP (LitPat l) = do { l2 <- repLiteral l; repPlit l2 }
727 repP (VarPat x) = do { x' <- lookupBinder x; repPvar x' }
728 repP (LazyPat p) = do { p1 <- repLP p; repPtilde p1 }
729 repP (AsPat x p) = do { x' <- lookupLBinder x; p1 <- repLP p; repPaspat x' p1 }
730 repP (ParPat p) = repLP p
731 repP (ListPat ps _) = do { qs <- repLPs ps; repPlist qs }
732 repP (TuplePat ps _) = do { qs <- repLPs ps; repPtup qs }
733 repP (ConPatIn dc details)
734 = do { con_str <- lookupLOcc dc
736 PrefixCon ps -> do { qs <- repLPs ps; repPcon con_str qs }
737 RecCon pairs -> do { vs <- sequence $ map lookupLOcc (map fst pairs)
738 ; ps <- sequence $ map repLP (map snd pairs)
739 ; fps <- zipWithM (\x y -> rep2 fieldPatName [unC x,unC y]) vs ps
740 ; fps' <- coreList fieldPatTyConName fps
741 ; repPrec con_str fps' }
742 InfixCon p1 p2 -> do { qs <- repLPs [p1,p2]; repPcon con_str qs }
744 repP (NPatIn l (Just _)) = panic "Can't cope with negative overloaded patterns yet (repP (NPatIn _ (Just _)))"
745 repP (NPatIn l Nothing) = do { a <- repOverloadedLiteral l; repPlit a }
746 repP other = panic "Exotic pattern inside meta brackets"
748 ----------------------------------------------------------
749 -- Declaration ordering helpers
751 sort_by_loc :: [(SrcSpan, a)] -> [(SrcSpan, a)]
752 sort_by_loc xs = sortBy comp xs
753 where comp x y = compare (fst x) (fst y)
755 de_loc :: [(a, b)] -> [b]
758 ----------------------------------------------------------
759 -- The meta-environment
761 -- A name/identifier association for fresh names of locally bound entities
762 type GenSymBind = (Name, Id) -- Gensym the string and bind it to the Id
763 -- I.e. (x, x_id) means
764 -- let x_id = gensym "x" in ...
766 -- Generate a fresh name for a locally bound entity
768 mkGenSyms :: [Name] -> DsM [GenSymBind]
769 -- We can use the existing name. For example:
770 -- [| \x_77 -> x_77 + x_77 |]
772 -- do { x_77 <- genSym "x"; .... }
773 -- We use the same x_77 in the desugared program, but with the type Bndr
776 -- We do make it an Internal name, though (hence localiseName)
778 -- Nevertheless, it's monadic because we have to generate nameTy
779 mkGenSyms ns = do { var_ty <- lookupType nameTyConName
780 ; return [(nm, mkLocalId (localiseName nm) var_ty) | nm <- ns] }
783 addBinds :: [GenSymBind] -> DsM a -> DsM a
784 -- Add a list of fresh names for locally bound entities to the
785 -- meta environment (which is part of the state carried around
786 -- by the desugarer monad)
787 addBinds bs m = dsExtendMetaEnv (mkNameEnv [(n,Bound id) | (n,id) <- bs]) m
789 -- Look up a locally bound name
791 lookupLBinder :: Located Name -> DsM (Core TH.Name)
792 lookupLBinder (L _ n) = lookupBinder n
794 lookupBinder :: Name -> DsM (Core TH.Name)
796 = do { mb_val <- dsLookupMetaEnv n;
798 Just (Bound x) -> return (coreVar x)
799 other -> pprPanic "Failed binder lookup:" (ppr n) }
801 -- Look up a name that is either locally bound or a global name
803 -- * If it is a global name, generate the "original name" representation (ie,
804 -- the <module>:<name> form) for the associated entity
806 lookupLOcc :: Located Name -> DsM (Core TH.Name)
807 -- Lookup an occurrence; it can't be a splice.
808 -- Use the in-scope bindings if they exist
809 lookupLOcc (L _ n) = lookupOcc n
811 lookupOcc :: Name -> DsM (Core TH.Name)
813 = do { mb_val <- dsLookupMetaEnv n ;
815 Nothing -> globalVar n
816 Just (Bound x) -> return (coreVar x)
817 Just (Splice _) -> pprPanic "repE:lookupOcc" (ppr n)
820 globalVar :: Name -> DsM (Core TH.Name)
821 -- Not bound by the meta-env
822 -- Could be top-level; or could be local
823 -- f x = $(g [| x |])
824 -- Here the x will be local
826 | isExternalName name
827 = do { MkC mod <- coreStringLit name_mod
828 ; MkC occ <- occNameLit name
829 ; rep2 mk_varg [mod,occ] }
831 = do { MkC occ <- occNameLit name
832 ; MkC uni <- coreIntLit (getKey (getUnique name))
833 ; rep2 mkNameUName [occ,uni] }
835 name_mod = moduleUserString (nameModule name)
836 name_occ = nameOccName name
837 mk_varg | OccName.isDataOcc name_occ = mkNameG_dName
838 | OccName.isVarOcc name_occ = mkNameG_vName
839 | OccName.isTcOcc name_occ = mkNameG_tcName
840 | otherwise = pprPanic "DsMeta.globalVar" (ppr name)
842 lookupType :: Name -- Name of type constructor (e.g. TH.ExpQ)
843 -> DsM Type -- The type
844 lookupType tc_name = do { tc <- dsLookupTyCon tc_name ;
845 return (mkGenTyConApp tc []) }
847 wrapGenSyns :: [GenSymBind]
848 -> Core (TH.Q a) -> DsM (Core (TH.Q a))
849 -- wrapGenSyns [(nm1,id1), (nm2,id2)] y
850 -- --> bindQ (gensym nm1) (\ id1 ->
851 -- bindQ (gensym nm2 (\ id2 ->
854 wrapGenSyns binds body@(MkC b)
855 = do { var_ty <- lookupType nameTyConName
858 [elt_ty] = tcTyConAppArgs (exprType b)
859 -- b :: Q a, so we can get the type 'a' by looking at the
860 -- argument type. NB: this relies on Q being a data/newtype,
861 -- not a type synonym
863 go var_ty [] = return body
864 go var_ty ((name,id) : binds)
865 = do { MkC body' <- go var_ty binds
866 ; lit_str <- occNameLit name
867 ; gensym_app <- repGensym lit_str
868 ; repBindQ var_ty elt_ty
869 gensym_app (MkC (Lam id body')) }
871 -- Just like wrapGenSym, but don't actually do the gensym
872 -- Instead use the existing name:
873 -- let x = "x" in ...
874 -- Only used for [Decl], and for the class ops in class
875 -- and instance decls
876 wrapNongenSyms :: [GenSymBind] -> Core a -> DsM (Core a)
877 wrapNongenSyms binds (MkC body)
878 = do { binds' <- mapM do_one binds ;
879 return (MkC (mkLets binds' body)) }
882 = do { MkC lit_str <- occNameLit name
883 ; MkC var <- rep2 mkNameName [lit_str]
884 ; return (NonRec id var) }
886 occNameLit :: Name -> DsM (Core String)
887 occNameLit n = coreStringLit (occNameUserString (nameOccName n))
890 -- %*********************************************************************
894 -- %*********************************************************************
896 -----------------------------------------------------------------------------
897 -- PHANTOM TYPES for consistency. In order to make sure we do this correct
898 -- we invent a new datatype which uses phantom types.
900 newtype Core a = MkC CoreExpr
903 rep2 :: Name -> [ CoreExpr ] -> DsM (Core a)
904 rep2 n xs = do { id <- dsLookupGlobalId n
905 ; return (MkC (foldl App (Var id) xs)) }
907 -- Then we make "repConstructors" which use the phantom types for each of the
908 -- smart constructors of the Meta.Meta datatypes.
911 -- %*********************************************************************
913 -- The 'smart constructors'
915 -- %*********************************************************************
917 --------------- Patterns -----------------
918 repPlit :: Core TH.Lit -> DsM (Core TH.Pat)
919 repPlit (MkC l) = rep2 litPName [l]
921 repPvar :: Core TH.Name -> DsM (Core TH.Pat)
922 repPvar (MkC s) = rep2 varPName [s]
924 repPtup :: Core [TH.Pat] -> DsM (Core TH.Pat)
925 repPtup (MkC ps) = rep2 tupPName [ps]
927 repPcon :: Core TH.Name -> Core [TH.Pat] -> DsM (Core TH.Pat)
928 repPcon (MkC s) (MkC ps) = rep2 conPName [s, ps]
930 repPrec :: Core TH.Name -> Core [(TH.Name,TH.Pat)] -> DsM (Core TH.Pat)
931 repPrec (MkC c) (MkC rps) = rep2 recPName [c,rps]
933 repPtilde :: Core TH.Pat -> DsM (Core TH.Pat)
934 repPtilde (MkC p) = rep2 tildePName [p]
936 repPaspat :: Core TH.Name -> Core TH.Pat -> DsM (Core TH.Pat)
937 repPaspat (MkC s) (MkC p) = rep2 asPName [s, p]
939 repPwild :: DsM (Core TH.Pat)
940 repPwild = rep2 wildPName []
942 repPlist :: Core [TH.Pat] -> DsM (Core TH.Pat)
943 repPlist (MkC ps) = rep2 listPName [ps]
945 --------------- Expressions -----------------
946 repVarOrCon :: Name -> Core TH.Name -> DsM (Core TH.ExpQ)
947 repVarOrCon vc str | isDataOcc (nameOccName vc) = repCon str
948 | otherwise = repVar str
950 repVar :: Core TH.Name -> DsM (Core TH.ExpQ)
951 repVar (MkC s) = rep2 varEName [s]
953 repCon :: Core TH.Name -> DsM (Core TH.ExpQ)
954 repCon (MkC s) = rep2 conEName [s]
956 repLit :: Core TH.Lit -> DsM (Core TH.ExpQ)
957 repLit (MkC c) = rep2 litEName [c]
959 repApp :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
960 repApp (MkC x) (MkC y) = rep2 appEName [x,y]
962 repLam :: Core [TH.Pat] -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
963 repLam (MkC ps) (MkC e) = rep2 lamEName [ps, e]
965 repTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
966 repTup (MkC es) = rep2 tupEName [es]
968 repCond :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
969 repCond (MkC x) (MkC y) (MkC z) = rep2 condEName [x,y,z]
971 repLetE :: Core [TH.DecQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
972 repLetE (MkC ds) (MkC e) = rep2 letEName [ds, e]
974 repCaseE :: Core TH.ExpQ -> Core [TH.MatchQ] -> DsM( Core TH.ExpQ)
975 repCaseE (MkC e) (MkC ms) = rep2 caseEName [e, ms]
977 repDoE :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ)
978 repDoE (MkC ss) = rep2 doEName [ss]
980 repComp :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ)
981 repComp (MkC ss) = rep2 compEName [ss]
983 repListExp :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
984 repListExp (MkC es) = rep2 listEName [es]
986 repSigExp :: Core TH.ExpQ -> Core TH.TypeQ -> DsM (Core TH.ExpQ)
987 repSigExp (MkC e) (MkC t) = rep2 sigEName [e,t]
989 repRecCon :: Core TH.Name -> Core [TH.FieldExp]-> DsM (Core TH.ExpQ)
990 repRecCon (MkC c) (MkC fs) = rep2 recCName [c,fs]
992 repRecUpd :: Core TH.ExpQ -> Core [TH.FieldExp] -> DsM (Core TH.ExpQ)
993 repRecUpd (MkC e) (MkC fs) = rep2 recUpdEName [e,fs]
995 repInfixApp :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
996 repInfixApp (MkC x) (MkC y) (MkC z) = rep2 infixAppName [x,y,z]
998 repSectionL :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
999 repSectionL (MkC x) (MkC y) = rep2 sectionLName [x,y]
1001 repSectionR :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1002 repSectionR (MkC x) (MkC y) = rep2 sectionRName [x,y]
1004 ------------ Right hand sides (guarded expressions) ----
1005 repGuarded :: Core [(TH.ExpQ, TH.ExpQ)] -> DsM (Core TH.BodyQ)
1006 repGuarded (MkC pairs) = rep2 guardedBName [pairs]
1008 repNormal :: Core TH.ExpQ -> DsM (Core TH.BodyQ)
1009 repNormal (MkC e) = rep2 normalBName [e]
1011 ------------- Stmts -------------------
1012 repBindSt :: Core TH.Pat -> Core TH.ExpQ -> DsM (Core TH.StmtQ)
1013 repBindSt (MkC p) (MkC e) = rep2 bindSName [p,e]
1015 repLetSt :: Core [TH.DecQ] -> DsM (Core TH.StmtQ)
1016 repLetSt (MkC ds) = rep2 letSName [ds]
1018 repNoBindSt :: Core TH.ExpQ -> DsM (Core TH.StmtQ)
1019 repNoBindSt (MkC e) = rep2 noBindSName [e]
1021 -------------- Range (Arithmetic sequences) -----------
1022 repFrom :: Core TH.ExpQ -> DsM (Core TH.ExpQ)
1023 repFrom (MkC x) = rep2 fromEName [x]
1025 repFromThen :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1026 repFromThen (MkC x) (MkC y) = rep2 fromThenEName [x,y]
1028 repFromTo :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1029 repFromTo (MkC x) (MkC y) = rep2 fromToEName [x,y]
1031 repFromThenTo :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1032 repFromThenTo (MkC x) (MkC y) (MkC z) = rep2 fromThenToEName [x,y,z]
1034 ------------ Match and Clause Tuples -----------
1035 repMatch :: Core TH.Pat -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.MatchQ)
1036 repMatch (MkC p) (MkC bod) (MkC ds) = rep2 matchName [p, bod, ds]
1038 repClause :: Core [TH.Pat] -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.ClauseQ)
1039 repClause (MkC ps) (MkC bod) (MkC ds) = rep2 clauseName [ps, bod, ds]
1041 -------------- Dec -----------------------------
1042 repVal :: Core TH.Pat -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ)
1043 repVal (MkC p) (MkC b) (MkC ds) = rep2 valDName [p, b, ds]
1045 repFun :: Core TH.Name -> Core [TH.ClauseQ] -> DsM (Core TH.DecQ)
1046 repFun (MkC nm) (MkC b) = rep2 funDName [nm, b]
1048 repData :: Core TH.CxtQ -> Core TH.Name -> Core [TH.Name] -> Core [TH.ConQ] -> Core [TH.Name] -> DsM (Core TH.DecQ)
1049 repData (MkC cxt) (MkC nm) (MkC tvs) (MkC cons) (MkC derivs)
1050 = rep2 dataDName [cxt, nm, tvs, cons, derivs]
1052 repNewtype :: Core TH.CxtQ -> Core TH.Name -> Core [TH.Name] -> Core TH.ConQ -> Core [TH.Name] -> DsM (Core TH.DecQ)
1053 repNewtype (MkC cxt) (MkC nm) (MkC tvs) (MkC con) (MkC derivs)
1054 = rep2 newtypeDName [cxt, nm, tvs, con, derivs]
1056 repTySyn :: Core TH.Name -> Core [TH.Name] -> Core TH.TypeQ -> DsM (Core TH.DecQ)
1057 repTySyn (MkC nm) (MkC tvs) (MkC rhs) = rep2 tySynDName [nm, tvs, rhs]
1059 repInst :: Core TH.CxtQ -> Core TH.TypeQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ)
1060 repInst (MkC cxt) (MkC ty) (MkC ds) = rep2 instanceDName [cxt, ty, ds]
1062 repClass :: Core TH.CxtQ -> Core TH.Name -> Core [TH.Name] -> Core [TH.DecQ] -> DsM (Core TH.DecQ)
1063 repClass (MkC cxt) (MkC cls) (MkC tvs) (MkC ds) = rep2 classDName [cxt, cls, tvs, ds]
1065 repProto :: Core TH.Name -> Core TH.TypeQ -> DsM (Core TH.DecQ)
1066 repProto (MkC s) (MkC ty) = rep2 sigDName [s, ty]
1068 repCtxt :: Core [TH.TypeQ] -> DsM (Core TH.CxtQ)
1069 repCtxt (MkC tys) = rep2 cxtName [tys]
1071 repConstr :: Core TH.Name -> HsConDetails Name (LBangType Name)
1072 -> DsM (Core TH.ConQ)
1073 repConstr con (PrefixCon ps)
1074 = do arg_tys <- mapM repBangTy ps
1075 arg_tys1 <- coreList strictTypeQTyConName arg_tys
1076 rep2 normalCName [unC con, unC arg_tys1]
1077 repConstr con (RecCon ips)
1078 = do arg_vs <- mapM lookupLOcc (map fst ips)
1079 arg_tys <- mapM repBangTy (map snd ips)
1080 arg_vtys <- zipWithM (\x y -> rep2 varStrictTypeName [unC x, unC y])
1082 arg_vtys' <- coreList varStrictTypeQTyConName arg_vtys
1083 rep2 recCName [unC con, unC arg_vtys']
1084 repConstr con (InfixCon st1 st2)
1085 = do arg1 <- repBangTy st1
1086 arg2 <- repBangTy st2
1087 rep2 infixCName [unC arg1, unC con, unC arg2]
1089 ------------ Types -------------------
1091 repTForall :: Core [TH.Name] -> Core TH.CxtQ -> Core TH.TypeQ -> DsM (Core TH.TypeQ)
1092 repTForall (MkC tvars) (MkC ctxt) (MkC ty)
1093 = rep2 forallTName [tvars, ctxt, ty]
1095 repTvar :: Core TH.Name -> DsM (Core TH.TypeQ)
1096 repTvar (MkC s) = rep2 varTName [s]
1098 repTapp :: Core TH.TypeQ -> Core TH.TypeQ -> DsM (Core TH.TypeQ)
1099 repTapp (MkC t1) (MkC t2) = rep2 appTName [t1,t2]
1101 repTapps :: Core TH.TypeQ -> [Core TH.TypeQ] -> DsM (Core TH.TypeQ)
1102 repTapps f [] = return f
1103 repTapps f (t:ts) = do { f1 <- repTapp f t; repTapps f1 ts }
1105 --------- Type constructors --------------
1107 repNamedTyCon :: Core TH.Name -> DsM (Core TH.TypeQ)
1108 repNamedTyCon (MkC s) = rep2 conTName [s]
1110 repTupleTyCon :: Int -> DsM (Core TH.TypeQ)
1111 -- Note: not Core Int; it's easier to be direct here
1112 repTupleTyCon i = rep2 tupleTName [mkIntExpr (fromIntegral i)]
1114 repArrowTyCon :: DsM (Core TH.TypeQ)
1115 repArrowTyCon = rep2 arrowTName []
1117 repListTyCon :: DsM (Core TH.TypeQ)
1118 repListTyCon = rep2 listTName []
1121 ----------------------------------------------------------
1124 repLiteral :: HsLit -> DsM (Core TH.Lit)
1126 = do lit' <- case lit of
1127 HsIntPrim i -> mk_integer i
1128 HsInt i -> mk_integer i
1129 HsFloatPrim r -> mk_rational r
1130 HsDoublePrim r -> mk_rational r
1132 lit_expr <- dsLit lit'
1133 rep2 lit_name [lit_expr]
1135 lit_name = case lit of
1136 HsInteger _ _ -> integerLName
1137 HsInt _ -> integerLName
1138 HsIntPrim _ -> intPrimLName
1139 HsFloatPrim _ -> floatPrimLName
1140 HsDoublePrim _ -> doublePrimLName
1141 HsChar _ -> charLName
1142 HsString _ -> stringLName
1143 HsRat _ _ -> rationalLName
1145 uh_oh = pprPanic "DsMeta.repLiteral: trying to represent exotic literal"
1148 mk_integer i = do integer_ty <- lookupType integerTyConName
1149 return $ HsInteger i integer_ty
1150 mk_rational r = do rat_ty <- lookupType rationalTyConName
1151 return $ HsRat r rat_ty
1153 repOverloadedLiteral :: HsOverLit -> DsM (Core TH.Lit)
1154 repOverloadedLiteral (HsIntegral i _) = do { lit <- mk_integer i; repLiteral lit }
1155 repOverloadedLiteral (HsFractional f _) = do { lit <- mk_rational f; repLiteral lit }
1156 -- The type Rational will be in the environment, becuase
1157 -- the smart constructor 'THSyntax.rationalL' uses it in its type,
1158 -- and rationalL is sucked in when any TH stuff is used
1160 --------------- Miscellaneous -------------------
1162 repGensym :: Core String -> DsM (Core (TH.Q TH.Name))
1163 repGensym (MkC lit_str) = rep2 newNameName [lit_str]
1165 repBindQ :: Type -> Type -- a and b
1166 -> Core (TH.Q a) -> Core (a -> TH.Q b) -> DsM (Core (TH.Q b))
1167 repBindQ ty_a ty_b (MkC x) (MkC y)
1168 = rep2 bindQName [Type ty_a, Type ty_b, x, y]
1170 repSequenceQ :: Type -> Core [TH.Q a] -> DsM (Core (TH.Q [a]))
1171 repSequenceQ ty_a (MkC list)
1172 = rep2 sequenceQName [Type ty_a, list]
1174 ------------ Lists and Tuples -------------------
1175 -- turn a list of patterns into a single pattern matching a list
1177 coreList :: Name -- Of the TyCon of the element type
1178 -> [Core a] -> DsM (Core [a])
1180 = do { elt_ty <- lookupType tc_name; return (coreList' elt_ty es) }
1182 coreList' :: Type -- The element type
1183 -> [Core a] -> Core [a]
1184 coreList' elt_ty es = MkC (mkListExpr elt_ty (map unC es ))
1186 nonEmptyCoreList :: [Core a] -> Core [a]
1187 -- The list must be non-empty so we can get the element type
1188 -- Otherwise use coreList
1189 nonEmptyCoreList [] = panic "coreList: empty argument"
1190 nonEmptyCoreList xs@(MkC x:_) = MkC (mkListExpr (exprType x) (map unC xs))
1192 corePair :: (Core a, Core b) -> Core (a,b)
1193 corePair (MkC x, MkC y) = MkC (mkCoreTup [x,y])
1195 coreStringLit :: String -> DsM (Core String)
1196 coreStringLit s = do { z <- mkStringLit s; return(MkC z) }
1198 coreIntLit :: Int -> DsM (Core Int)
1199 coreIntLit i = return (MkC (mkIntExpr (fromIntegral i)))
1201 coreVar :: Id -> Core TH.Name -- The Id has type Name
1202 coreVar id = MkC (Var id)
1206 -- %************************************************************************
1208 -- The known-key names for Template Haskell
1210 -- %************************************************************************
1212 -- To add a name, do three things
1214 -- 1) Allocate a key
1216 -- 3) Add the name to knownKeyNames
1218 templateHaskellNames :: [Name]
1219 -- The names that are implicitly mentioned by ``bracket''
1220 -- Should stay in sync with the import list of DsMeta
1222 templateHaskellNames = [
1223 returnQName, bindQName, sequenceQName, newNameName, liftName,
1224 mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName, mkNameUName,
1227 charLName, stringLName, integerLName, intPrimLName,
1228 floatPrimLName, doublePrimLName, rationalLName,
1230 litPName, varPName, tupPName, conPName, tildePName,
1231 asPName, wildPName, recPName, listPName,
1239 varEName, conEName, litEName, appEName, infixEName,
1240 infixAppName, sectionLName, sectionRName, lamEName, tupEName,
1241 condEName, letEName, caseEName, doEName, compEName,
1242 fromEName, fromThenEName, fromToEName, fromThenToEName,
1243 listEName, sigEName, recConEName, recUpdEName,
1247 guardedBName, normalBName,
1249 bindSName, letSName, noBindSName, parSName,
1251 funDName, valDName, dataDName, newtypeDName, tySynDName,
1252 classDName, instanceDName, sigDName,
1256 isStrictName, notStrictName,
1258 normalCName, recCName, infixCName,
1264 forallTName, varTName, conTName, appTName,
1265 tupleTName, arrowTName, listTName,
1268 qTyConName, nameTyConName, patTyConName, fieldPatTyConName, matchQTyConName,
1269 clauseQTyConName, expQTyConName, fieldExpTyConName, stmtQTyConName,
1270 decQTyConName, conQTyConName, strictTypeQTyConName,
1271 varStrictTypeQTyConName, typeQTyConName, expTyConName, decTyConName,
1272 typeTyConName, matchTyConName, clauseTyConName]
1274 tH_SYN_Name = mkModuleName "Language.Haskell.TH.THSyntax"
1275 tH_LIB_Name = mkModuleName "Language.Haskell.TH.THLib"
1278 -- NB: the THSyntax module comes from the "haskell-src" package
1279 thSyn = mkModule thPackage tH_SYN_Name
1280 thLib = mkModule thPackage tH_LIB_Name
1282 mk_known_key_name mod space str uniq
1283 = mkExternalName uniq mod (mkOccFS space str)
1286 libFun = mk_known_key_name thLib OccName.varName
1287 libTc = mk_known_key_name thLib OccName.tcName
1288 thFun = mk_known_key_name thSyn OccName.varName
1289 thTc = mk_known_key_name thSyn OccName.tcName
1291 -------------------- THSyntax -----------------------
1292 qTyConName = thTc FSLIT("Q") qTyConKey
1293 nameTyConName = thTc FSLIT("Name") nameTyConKey
1294 fieldExpTyConName = thTc FSLIT("FieldExp") fieldExpTyConKey
1295 patTyConName = thTc FSLIT("Pat") patTyConKey
1296 fieldPatTyConName = thTc FSLIT("FieldPat") fieldPatTyConKey
1297 expTyConName = thTc FSLIT("Exp") expTyConKey
1298 decTyConName = thTc FSLIT("Dec") decTyConKey
1299 typeTyConName = thTc FSLIT("Type") typeTyConKey
1300 matchTyConName = thTc FSLIT("Match") matchTyConKey
1301 clauseTyConName = thTc FSLIT("Clause") clauseTyConKey
1303 returnQName = thFun FSLIT("returnQ") returnQIdKey
1304 bindQName = thFun FSLIT("bindQ") bindQIdKey
1305 sequenceQName = thFun FSLIT("sequenceQ") sequenceQIdKey
1306 newNameName = thFun FSLIT("newName") newNameIdKey
1307 liftName = thFun FSLIT("lift") liftIdKey
1308 mkNameName = thFun FSLIT("mkName") mkNameIdKey
1309 mkNameG_vName = thFun FSLIT("mkNameG_v") mkNameG_vIdKey
1310 mkNameG_dName = thFun FSLIT("mkNameG_d") mkNameG_dIdKey
1311 mkNameG_tcName = thFun FSLIT("mkNameG_tc") mkNameG_tcIdKey
1312 mkNameUName = thFun FSLIT("mkNameU") mkNameUIdKey
1315 -------------------- THLib -----------------------
1317 charLName = libFun FSLIT("charL") charLIdKey
1318 stringLName = libFun FSLIT("stringL") stringLIdKey
1319 integerLName = libFun FSLIT("integerL") integerLIdKey
1320 intPrimLName = libFun FSLIT("intPrimL") intPrimLIdKey
1321 floatPrimLName = libFun FSLIT("floatPrimL") floatPrimLIdKey
1322 doublePrimLName = libFun FSLIT("doublePrimL") doublePrimLIdKey
1323 rationalLName = libFun FSLIT("rationalL") rationalLIdKey
1326 litPName = libFun FSLIT("litP") litPIdKey
1327 varPName = libFun FSLIT("varP") varPIdKey
1328 tupPName = libFun FSLIT("tupP") tupPIdKey
1329 conPName = libFun FSLIT("conP") conPIdKey
1330 tildePName = libFun FSLIT("tildeP") tildePIdKey
1331 asPName = libFun FSLIT("asP") asPIdKey
1332 wildPName = libFun FSLIT("wildP") wildPIdKey
1333 recPName = libFun FSLIT("recP") recPIdKey
1334 listPName = libFun FSLIT("listP") listPIdKey
1336 -- type FieldPat = ...
1337 fieldPatName = libFun FSLIT("fieldPat") fieldPatIdKey
1340 matchName = libFun FSLIT("match") matchIdKey
1342 -- data Clause = ...
1343 clauseName = libFun FSLIT("clause") clauseIdKey
1346 varEName = libFun FSLIT("varE") varEIdKey
1347 conEName = libFun FSLIT("conE") conEIdKey
1348 litEName = libFun FSLIT("litE") litEIdKey
1349 appEName = libFun FSLIT("appE") appEIdKey
1350 infixEName = libFun FSLIT("infixE") infixEIdKey
1351 infixAppName = libFun FSLIT("infixApp") infixAppIdKey
1352 sectionLName = libFun FSLIT("sectionL") sectionLIdKey
1353 sectionRName = libFun FSLIT("sectionR") sectionRIdKey
1354 lamEName = libFun FSLIT("lamE") lamEIdKey
1355 tupEName = libFun FSLIT("tupE") tupEIdKey
1356 condEName = libFun FSLIT("condE") condEIdKey
1357 letEName = libFun FSLIT("letE") letEIdKey
1358 caseEName = libFun FSLIT("caseE") caseEIdKey
1359 doEName = libFun FSLIT("doE") doEIdKey
1360 compEName = libFun FSLIT("compE") compEIdKey
1361 -- ArithSeq skips a level
1362 fromEName = libFun FSLIT("fromE") fromEIdKey
1363 fromThenEName = libFun FSLIT("fromThenE") fromThenEIdKey
1364 fromToEName = libFun FSLIT("fromToE") fromToEIdKey
1365 fromThenToEName = libFun FSLIT("fromThenToE") fromThenToEIdKey
1367 listEName = libFun FSLIT("listE") listEIdKey
1368 sigEName = libFun FSLIT("sigE") sigEIdKey
1369 recConEName = libFun FSLIT("recConE") recConEIdKey
1370 recUpdEName = libFun FSLIT("recUpdE") recUpdEIdKey
1372 -- type FieldExp = ...
1373 fieldExpName = libFun FSLIT("fieldExp") fieldExpIdKey
1376 guardedBName = libFun FSLIT("guardedB") guardedBIdKey
1377 normalBName = libFun FSLIT("normalB") normalBIdKey
1380 bindSName = libFun FSLIT("bindS") bindSIdKey
1381 letSName = libFun FSLIT("letS") letSIdKey
1382 noBindSName = libFun FSLIT("noBindS") noBindSIdKey
1383 parSName = libFun FSLIT("parS") parSIdKey
1386 funDName = libFun FSLIT("funD") funDIdKey
1387 valDName = libFun FSLIT("valD") valDIdKey
1388 dataDName = libFun FSLIT("dataD") dataDIdKey
1389 newtypeDName = libFun FSLIT("newtypeD") newtypeDIdKey
1390 tySynDName = libFun FSLIT("tySynD") tySynDIdKey
1391 classDName = libFun FSLIT("classD") classDIdKey
1392 instanceDName = libFun FSLIT("instanceD") instanceDIdKey
1393 sigDName = libFun FSLIT("sigD") sigDIdKey
1396 cxtName = libFun FSLIT("cxt") cxtIdKey
1398 -- data Strict = ...
1399 isStrictName = libFun FSLIT("isStrict") isStrictKey
1400 notStrictName = libFun FSLIT("notStrict") notStrictKey
1403 normalCName = libFun FSLIT("normalC") normalCIdKey
1404 recCName = libFun FSLIT("recC") recCIdKey
1405 infixCName = libFun FSLIT("infixC") infixCIdKey
1407 -- type StrictType = ...
1408 strictTypeName = libFun FSLIT("strictType") strictTKey
1410 -- type VarStrictType = ...
1411 varStrictTypeName = libFun FSLIT("varStrictType") varStrictTKey
1414 forallTName = libFun FSLIT("forallT") forallTIdKey
1415 varTName = libFun FSLIT("varT") varTIdKey
1416 conTName = libFun FSLIT("conT") conTIdKey
1417 tupleTName = libFun FSLIT("tupleT") tupleTIdKey
1418 arrowTName = libFun FSLIT("arrowT") arrowTIdKey
1419 listTName = libFun FSLIT("listT") listTIdKey
1420 appTName = libFun FSLIT("appT") appTIdKey
1422 matchQTyConName = libTc FSLIT("MatchQ") matchQTyConKey
1423 clauseQTyConName = libTc FSLIT("ClauseQ") clauseQTyConKey
1424 expQTyConName = libTc FSLIT("ExpQ") expQTyConKey
1425 stmtQTyConName = libTc FSLIT("StmtQ") stmtQTyConKey
1426 decQTyConName = libTc FSLIT("DecQ") decQTyConKey
1427 conQTyConName = libTc FSLIT("ConQ") conQTyConKey
1428 strictTypeQTyConName = libTc FSLIT("StrictTypeQ") strictTypeQTyConKey
1429 varStrictTypeQTyConName = libTc FSLIT("VarStrictTypeQ") varStrictTypeQTyConKey
1430 typeQTyConName = libTc FSLIT("TypeQ") typeQTyConKey
1432 -- TyConUniques available: 100-119
1433 -- Check in PrelNames if you want to change this
1435 expTyConKey = mkPreludeTyConUnique 100
1436 matchTyConKey = mkPreludeTyConUnique 101
1437 clauseTyConKey = mkPreludeTyConUnique 102
1438 qTyConKey = mkPreludeTyConUnique 103
1439 expQTyConKey = mkPreludeTyConUnique 104
1440 decQTyConKey = mkPreludeTyConUnique 105
1441 patTyConKey = mkPreludeTyConUnique 106
1442 matchQTyConKey = mkPreludeTyConUnique 107
1443 clauseQTyConKey = mkPreludeTyConUnique 108
1444 stmtQTyConKey = mkPreludeTyConUnique 109
1445 conQTyConKey = mkPreludeTyConUnique 110
1446 typeQTyConKey = mkPreludeTyConUnique 111
1447 typeTyConKey = mkPreludeTyConUnique 112
1448 decTyConKey = mkPreludeTyConUnique 113
1449 varStrictTypeQTyConKey = mkPreludeTyConUnique 114
1450 strictTypeQTyConKey = mkPreludeTyConUnique 115
1451 fieldExpTyConKey = mkPreludeTyConUnique 116
1452 fieldPatTyConKey = mkPreludeTyConUnique 117
1453 nameTyConKey = mkPreludeTyConUnique 118
1455 -- IdUniques available: 200-299
1456 -- If you want to change this, make sure you check in PrelNames
1458 returnQIdKey = mkPreludeMiscIdUnique 200
1459 bindQIdKey = mkPreludeMiscIdUnique 201
1460 sequenceQIdKey = mkPreludeMiscIdUnique 202
1461 liftIdKey = mkPreludeMiscIdUnique 203
1462 newNameIdKey = mkPreludeMiscIdUnique 204
1463 mkNameIdKey = mkPreludeMiscIdUnique 205
1464 mkNameG_vIdKey = mkPreludeMiscIdUnique 206
1465 mkNameG_dIdKey = mkPreludeMiscIdUnique 207
1466 mkNameG_tcIdKey = mkPreludeMiscIdUnique 208
1467 mkNameUIdKey = mkPreludeMiscIdUnique 209
1471 charLIdKey = mkPreludeMiscIdUnique 210
1472 stringLIdKey = mkPreludeMiscIdUnique 211
1473 integerLIdKey = mkPreludeMiscIdUnique 212
1474 intPrimLIdKey = mkPreludeMiscIdUnique 213
1475 floatPrimLIdKey = mkPreludeMiscIdUnique 214
1476 doublePrimLIdKey = mkPreludeMiscIdUnique 215
1477 rationalLIdKey = mkPreludeMiscIdUnique 216
1480 litPIdKey = mkPreludeMiscIdUnique 220
1481 varPIdKey = mkPreludeMiscIdUnique 221
1482 tupPIdKey = mkPreludeMiscIdUnique 222
1483 conPIdKey = mkPreludeMiscIdUnique 223
1484 tildePIdKey = mkPreludeMiscIdUnique 224
1485 asPIdKey = mkPreludeMiscIdUnique 225
1486 wildPIdKey = mkPreludeMiscIdUnique 226
1487 recPIdKey = mkPreludeMiscIdUnique 227
1488 listPIdKey = mkPreludeMiscIdUnique 228
1490 -- type FieldPat = ...
1491 fieldPatIdKey = mkPreludeMiscIdUnique 230
1494 matchIdKey = mkPreludeMiscIdUnique 231
1496 -- data Clause = ...
1497 clauseIdKey = mkPreludeMiscIdUnique 232
1500 varEIdKey = mkPreludeMiscIdUnique 240
1501 conEIdKey = mkPreludeMiscIdUnique 241
1502 litEIdKey = mkPreludeMiscIdUnique 242
1503 appEIdKey = mkPreludeMiscIdUnique 243
1504 infixEIdKey = mkPreludeMiscIdUnique 244
1505 infixAppIdKey = mkPreludeMiscIdUnique 245
1506 sectionLIdKey = mkPreludeMiscIdUnique 246
1507 sectionRIdKey = mkPreludeMiscIdUnique 247
1508 lamEIdKey = mkPreludeMiscIdUnique 248
1509 tupEIdKey = mkPreludeMiscIdUnique 249
1510 condEIdKey = mkPreludeMiscIdUnique 250
1511 letEIdKey = mkPreludeMiscIdUnique 251
1512 caseEIdKey = mkPreludeMiscIdUnique 252
1513 doEIdKey = mkPreludeMiscIdUnique 253
1514 compEIdKey = mkPreludeMiscIdUnique 254
1515 fromEIdKey = mkPreludeMiscIdUnique 255
1516 fromThenEIdKey = mkPreludeMiscIdUnique 256
1517 fromToEIdKey = mkPreludeMiscIdUnique 257
1518 fromThenToEIdKey = mkPreludeMiscIdUnique 258
1519 listEIdKey = mkPreludeMiscIdUnique 259
1520 sigEIdKey = mkPreludeMiscIdUnique 260
1521 recConEIdKey = mkPreludeMiscIdUnique 261
1522 recUpdEIdKey = mkPreludeMiscIdUnique 262
1524 -- type FieldExp = ...
1525 fieldExpIdKey = mkPreludeMiscIdUnique 265
1528 guardedBIdKey = mkPreludeMiscIdUnique 266
1529 normalBIdKey = mkPreludeMiscIdUnique 267
1532 bindSIdKey = mkPreludeMiscIdUnique 268
1533 letSIdKey = mkPreludeMiscIdUnique 269
1534 noBindSIdKey = mkPreludeMiscIdUnique 270
1535 parSIdKey = mkPreludeMiscIdUnique 271
1538 funDIdKey = mkPreludeMiscIdUnique 272
1539 valDIdKey = mkPreludeMiscIdUnique 273
1540 dataDIdKey = mkPreludeMiscIdUnique 274
1541 newtypeDIdKey = mkPreludeMiscIdUnique 275
1542 tySynDIdKey = mkPreludeMiscIdUnique 276
1543 classDIdKey = mkPreludeMiscIdUnique 277
1544 instanceDIdKey = mkPreludeMiscIdUnique 278
1545 sigDIdKey = mkPreludeMiscIdUnique 279
1548 cxtIdKey = mkPreludeMiscIdUnique 280
1550 -- data Strict = ...
1551 isStrictKey = mkPreludeMiscIdUnique 281
1552 notStrictKey = mkPreludeMiscIdUnique 282
1555 normalCIdKey = mkPreludeMiscIdUnique 283
1556 recCIdKey = mkPreludeMiscIdUnique 284
1557 infixCIdKey = mkPreludeMiscIdUnique 285
1559 -- type StrictType = ...
1560 strictTKey = mkPreludeMiscIdUnique 2286
1562 -- type VarStrictType = ...
1563 varStrictTKey = mkPreludeMiscIdUnique 287
1566 forallTIdKey = mkPreludeMiscIdUnique 290
1567 varTIdKey = mkPreludeMiscIdUnique 291
1568 conTIdKey = mkPreludeMiscIdUnique 292
1569 tupleTIdKey = mkPreludeMiscIdUnique 294
1570 arrowTIdKey = mkPreludeMiscIdUnique 295
1571 listTIdKey = mkPreludeMiscIdUnique 296
1572 appTIdKey = mkPreludeMiscIdUnique 293