2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcSplice]{Template Haskell splices}
7 module TcSplice( tcSpliceExpr, tcSpliceDecls, tcBracket ) where
9 #include "HsVersions.h"
11 import HscMain ( compileExpr )
12 import TcRnDriver ( tcTopSrcDecls )
13 -- These imports are the reason that TcSplice
14 -- is very high up the module hierarchy
16 import qualified Language.Haskell.TH.THSyntax as TH
17 -- THSyntax gives access to internal functions and data types
19 import HscTypes ( HscEnv(..) )
20 import HsSyn ( HsBracket(..), HsExpr(..) )
21 import Convert ( convertToHsExpr, convertToHsDecls )
22 import RnExpr ( rnExpr )
23 import RnEnv ( lookupFixityRn )
24 import RdrHsSyn ( RdrNameHsExpr, RdrNameHsDecl )
25 import RnHsSyn ( RenamedHsExpr )
26 import TcExpr ( tcCheckRho, tcMonoExpr )
27 import TcHsSyn ( TcExpr, TypecheckedHsExpr, mkHsLet, zonkTopExpr )
28 import TcSimplify ( tcSimplifyTop, tcSimplifyBracket )
29 import TcUnify ( Expected, zapExpectedTo, zapExpectedType )
30 import TcType ( TcType, openTypeKind, mkAppTy, tcSplitSigmaTy )
31 import TcEnv ( spliceOK, tcMetaTy, bracketOK, tcLookup )
32 import TcMType ( newTyVarTy, UserTypeCtxt(ExprSigCtxt), zonkTcType, zonkTcTyVar )
33 import TcHsType ( tcHsSigType )
34 import TypeRep ( Type(..), PredType(..), TyThing(..) ) -- For reification
35 import Name ( Name, NamedThing(..), nameOccName, nameModule, isExternalName )
37 import Var ( TyVar, idType )
38 import Module ( moduleUserString, mkModuleName )
40 import IfaceEnv ( lookupOrig )
42 import Class ( Class, classBigSig )
43 import TyCon ( TyCon, tyConTheta, tyConTyVars, getSynTyConDefn, isSynTyCon, isNewTyCon, tyConDataCons )
44 import DataCon ( DataCon, dataConTyCon, dataConOrigArgTys, dataConStrictMarks,
45 dataConName, dataConFieldLabels, dataConWrapId )
46 import Id ( idName, globalIdDetails )
47 import IdInfo ( GlobalIdDetails(..) )
48 import TysWiredIn ( mkListTy )
49 import DsMeta ( expQTyConName, typeQTyConName, decTyConName, qTyConName, nameTyConName )
50 import ErrUtils ( Message )
52 import Unique ( Unique, Uniquable(..), getKey )
53 import IOEnv ( IOEnv )
54 import BasicTypes ( StrictnessMark(..), Fixity(..), FixityDirection(..) )
55 import Module ( moduleUserString )
56 import Panic ( showException )
57 import GHC.Base ( unsafeCoerce#, Int(..) ) -- Should have a better home in the module hierarchy
58 import Monad ( liftM )
59 import FastString ( LitString )
60 import FastTypes ( iBox )
64 %************************************************************************
66 \subsection{Main interface + stubs for the non-GHCI case
68 %************************************************************************
71 tcSpliceDecls :: RenamedHsExpr -> TcM [RdrNameHsDecl]
79 tcSpliceExpr n e ty = pprPanic "Cant do tcSpliceExpr without GHCi" (ppr e)
80 tcSpliceDecls e = pprPanic "Cant do tcSpliceDecls without GHCi" (ppr e)
84 %************************************************************************
86 \subsection{Quoting an expression}
88 %************************************************************************
91 tcBracket :: HsBracket Name -> Expected TcType -> TcM TcExpr
92 tcBracket brack res_ty
93 = getStage `thenM` \ level ->
94 case bracketOK level of {
95 Nothing -> failWithTc (illegalBracket level) ;
98 -- Typecheck expr to make sure it is valid,
99 -- but throw away the results. We'll type check
100 -- it again when we actually use it.
101 newMutVar [] `thenM` \ pending_splices ->
102 getLIEVar `thenM` \ lie_var ->
104 setStage (Brack next_level pending_splices lie_var) (
105 getLIE (tc_bracket brack)
106 ) `thenM` \ (meta_ty, lie) ->
107 tcSimplifyBracket lie `thenM_`
109 -- Make the expected type have the right shape
110 zapExpectedTo res_ty meta_ty `thenM_`
112 -- Return the original expression, not the type-decorated one
113 readMutVar pending_splices `thenM` \ pendings ->
114 returnM (HsBracketOut brack pendings)
117 tc_bracket :: HsBracket Name -> TcM TcType
119 = tcMetaTy nameTyConName
120 -- Result type is Var (not Q-monadic)
122 tc_bracket (ExpBr expr)
123 = newTyVarTy openTypeKind `thenM` \ any_ty ->
124 tcCheckRho expr any_ty `thenM_`
125 tcMetaTy expQTyConName
126 -- Result type is Expr (= Q Exp)
128 tc_bracket (TypBr typ)
129 = tcHsSigType ExprSigCtxt typ `thenM_`
130 tcMetaTy typeQTyConName
131 -- Result type is Type (= Q Typ)
133 tc_bracket (DecBr decls)
134 = tcTopSrcDecls decls `thenM_`
135 -- Typecheck the declarations, dicarding the result
136 -- We'll get all that stuff later, when we splice it in
138 tcMetaTy decTyConName `thenM` \ decl_ty ->
139 tcMetaTy qTyConName `thenM` \ q_ty ->
140 returnM (mkAppTy q_ty (mkListTy decl_ty))
141 -- Result type is Q [Dec]
145 %************************************************************************
147 \subsection{Splicing an expression}
149 %************************************************************************
152 tcSpliceExpr name expr res_ty
153 = getStage `thenM` \ level ->
154 case spliceOK level of {
155 Nothing -> failWithTc (illegalSplice level) ;
159 Comp -> tcTopSplice expr res_ty ;
160 Brack _ ps_var lie_var ->
162 -- A splice inside brackets
163 -- NB: ignore res_ty, apart from zapping it to a mono-type
164 -- e.g. [| reverse $(h 4) |]
165 -- Here (h 4) :: Q Exp
166 -- but $(h 4) :: forall a.a i.e. anything!
168 zapExpectedType res_ty `thenM_`
169 tcMetaTy expQTyConName `thenM` \ meta_exp_ty ->
170 setStage (Splice next_level) (
172 tcCheckRho expr meta_exp_ty
175 -- Write the pending splice into the bucket
176 readMutVar ps_var `thenM` \ ps ->
177 writeMutVar ps_var ((name,expr') : ps) `thenM_`
179 returnM (panic "tcSpliceExpr") -- The returned expression is ignored
182 -- tcTopSplice used to have this:
183 -- Note that we do not decrement the level (to -1) before
184 -- typechecking the expression. For example:
185 -- f x = $( ...$(g 3) ... )
186 -- The recursive call to tcMonoExpr will simply expand the
187 -- inner escape before dealing with the outer one
189 tcTopSplice expr res_ty
190 = tcMetaTy expQTyConName `thenM` \ meta_exp_ty ->
192 -- Typecheck the expression
193 tcTopSpliceExpr expr meta_exp_ty `thenM` \ zonked_q_expr ->
195 -- Run the expression
196 traceTc (text "About to run" <+> ppr zonked_q_expr) `thenM_`
197 runMetaE zonked_q_expr `thenM` \ simple_expr ->
200 -- simple_expr :: TH.Exp
202 expr2 :: RdrNameHsExpr
203 expr2 = convertToHsExpr simple_expr
205 traceTc (text "Got result" <+> ppr expr2) `thenM_`
207 showSplice "expression"
208 zonked_q_expr (ppr expr2) `thenM_`
210 -- Rename it, but bale out if there are errors
211 -- otherwise the type checker just gives more spurious errors
212 checkNoErrs (rnExpr expr2) `thenM` \ (exp3, fvs) ->
214 tcMonoExpr exp3 res_ty
217 tcTopSpliceExpr :: RenamedHsExpr -> TcType -> TcM TypecheckedHsExpr
218 -- Type check an expression that is the body of a top-level splice
219 -- (the caller will compile and run it)
220 tcTopSpliceExpr expr meta_ty
221 = checkNoErrs $ -- checkNoErrs: must not try to run the thing
222 -- if the type checker fails!
224 setStage topSpliceStage $
226 -- Typecheck the expression
227 getLIE (tcCheckRho expr meta_ty) `thenM` \ (expr', lie) ->
229 -- Solve the constraints
230 tcSimplifyTop lie `thenM` \ const_binds ->
233 zonkTopExpr (mkHsLet const_binds expr')
237 %************************************************************************
239 \subsection{Splicing an expression}
241 %************************************************************************
244 -- Always at top level
246 = tcMetaTy decTyConName `thenM` \ meta_dec_ty ->
247 tcMetaTy qTyConName `thenM` \ meta_q_ty ->
249 list_q = mkAppTy meta_q_ty (mkListTy meta_dec_ty)
251 tcTopSpliceExpr expr list_q `thenM` \ zonked_q_expr ->
253 -- Run the expression
254 traceTc (text "About to run" <+> ppr zonked_q_expr) `thenM_`
255 runMetaD zonked_q_expr `thenM` \ simple_expr ->
256 -- simple_expr :: [TH.Dec]
257 -- decls :: [RdrNameHsDecl]
258 handleErrors (convertToHsDecls simple_expr) `thenM` \ decls ->
259 traceTc (text "Got result" <+> vcat (map ppr decls)) `thenM_`
260 showSplice "declarations"
261 zonked_q_expr (vcat (map ppr decls)) `thenM_`
264 where handleErrors :: [Either a Message] -> TcM [a]
265 handleErrors [] = return []
266 handleErrors (Left x:xs) = liftM (x:) (handleErrors xs)
267 handleErrors (Right m:xs) = do addErrTc m
272 %************************************************************************
274 \subsection{Running an expression}
276 %************************************************************************
279 runMetaE :: TypecheckedHsExpr -- Of type (Q Exp)
280 -> TcM TH.Exp -- Of type Exp
281 runMetaE e = runMeta e
283 runMetaD :: TypecheckedHsExpr -- Of type Q [Dec]
284 -> TcM [TH.Dec] -- Of type [Dec]
285 runMetaD e = runMeta e
287 runMeta :: TypecheckedHsExpr -- Of type X
288 -> TcM t -- Of type t
290 = do { hsc_env <- getTopEnv
291 ; tcg_env <- getGblEnv
292 ; this_mod <- getModule
293 ; let type_env = tcg_type_env tcg_env
294 rdr_env = tcg_rdr_env tcg_env
295 -- Wrap the compile-and-run in an exception-catcher
296 -- Compiling might fail if linking fails
297 -- Running might fail if it throws an exception
298 ; either_tval <- tryM $ do
300 hval <- ioToTcRn (HscMain.compileExpr
302 rdr_env type_env expr)
303 -- Coerce it to Q t, and run it
304 ; TH.runQ (unsafeCoerce# hval) }
306 ; case either_tval of
307 Left exn -> failWithTc (vcat [text "Exception when trying to run compile-time code:",
308 nest 4 (vcat [text "Code:" <+> ppr expr,
309 text ("Exn: " ++ Panic.showException exn)])])
310 Right v -> returnM v }
313 To call runQ in the Tc monad, we need to make TcM an instance of Quasi:
316 instance TH.Quasi (IOEnv (Env TcGblEnv TcLclEnv)) where
317 qNewName s = do { u <- newUnique
319 ; return (TH.mkNameU s i) }
321 qReport True msg = addErr (text msg)
322 qReport False msg = addReport (text msg)
324 qCurrentModule = do { m <- getModule; return (moduleUserString m) }
328 qRunIO io = ioToTcRn io
332 %************************************************************************
334 \subsection{Errors and contexts}
336 %************************************************************************
339 showSplice :: String -> TypecheckedHsExpr -> SDoc -> TcM ()
340 showSplice what before after
341 = getSrcLocM `thenM` \ loc ->
342 traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what,
343 nest 2 (sep [nest 2 (ppr before),
348 = ptext SLIT("Illegal bracket at level") <+> ppr level
351 = ptext SLIT("Illegal splice at level") <+> ppr level
357 %************************************************************************
361 %************************************************************************
365 reify :: TH.Name -> TcM TH.Info
366 reify (TH.Name occ (TH.NameG th_ns mod))
367 = do { name <- lookupOrig (mkModuleName (TH.modString mod))
368 (OccName.mkOccName ghc_ns (TH.occString occ))
369 ; thing <- tcLookup name
373 ghc_ns = case th_ns of
374 TH.DataName -> dataName
375 TH.TcClsName -> tcClsName
376 TH.VarName -> varName
378 ------------------------------
379 reifyThing :: TcTyThing -> TcM TH.Info
380 -- The only reason this is monadic is for error reporting,
381 -- which in turn is mainly for the case when TH can't express
382 -- some random GHC extension
384 reifyThing (AGlobal (AnId id))
385 = do { ty <- reifyType (idType id)
386 ; fix <- reifyFixity (idName id)
387 ; let v = reifyName id
388 ; case globalIdDetails id of
389 ClassOpId cls -> return (TH.ClassOpI v ty (reifyName cls) fix)
390 other -> return (TH.VarI v ty Nothing fix)
393 reifyThing (AGlobal (ATyCon tc)) = do { dec <- reifyTyCon tc; return (TH.TyConI dec) }
394 reifyThing (AGlobal (AClass cls)) = do { dec <- reifyClass cls; return (TH.ClassI dec) }
395 reifyThing (AGlobal (ADataCon dc))
396 = do { let name = dataConName dc
397 ; ty <- reifyType (idType (dataConWrapId dc))
398 ; fix <- reifyFixity name
399 ; return (TH.DataConI (reifyName name) ty (reifyName (dataConTyCon dc)) fix) }
401 reifyThing (ATcId id _ _)
402 = do { ty1 <- zonkTcType (idType id) -- Make use of all the info we have, even
403 -- though it may be incomplete
404 ; ty2 <- reifyType ty1
405 ; fix <- reifyFixity (idName id)
406 ; return (TH.VarI (reifyName id) ty2 Nothing fix) }
408 reifyThing (ATyVar tv)
409 = do { ty1 <- zonkTcTyVar tv
410 ; ty2 <- reifyType ty1
411 ; return (TH.TyVarI (reifyName tv) ty2) }
413 ------------------------------
414 reifyTyCon :: TyCon -> TcM TH.Dec
417 = do { let (tvs, rhs) = getSynTyConDefn tc
418 ; rhs' <- reifyType rhs
419 ; return (TH.TySynD (reifyName tc) (reifyTyVars tvs) rhs') }
422 = do { cxt <- reifyCxt (tyConTheta tc)
423 ; con <- reifyDataCon (head (tyConDataCons tc))
424 ; return (TH.NewtypeD cxt (reifyName tc) (reifyTyVars (tyConTyVars tc))
425 con [{- Don't know about deriving -}]) }
427 | otherwise -- Algebraic
428 = do { cxt <- reifyCxt (tyConTheta tc)
429 ; cons <- mapM reifyDataCon (tyConDataCons tc)
430 ; return (TH.DataD cxt (reifyName tc) (reifyTyVars (tyConTyVars tc))
431 cons [{- Don't know about deriving -}]) }
433 reifyDataCon :: DataCon -> TcM TH.Con
435 = do { arg_tys <- reifyTypes (dataConOrigArgTys dc)
436 ; let stricts = map reifyStrict (dataConStrictMarks dc)
437 fields = dataConFieldLabels dc
438 ; if null fields then
439 return (TH.NormalC (reifyName dc) (stricts `zip` arg_tys))
441 return (TH.RecC (reifyName dc) (zip3 (map reifyName fields) stricts arg_tys)) }
442 -- NB: we don't remember whether the constructor was declared in an infix way
444 ------------------------------
445 reifyClass :: Class -> TcM TH.Dec
447 = do { cxt <- reifyCxt theta
448 ; ops <- mapM reify_op op_stuff
449 ; return (TH.ClassD cxt (reifyName cls) (reifyTyVars tvs) ops) }
451 (tvs, theta, _, op_stuff) = classBigSig cls
452 reify_op (op, _) = do { ty <- reifyType (idType op)
453 ; return (TH.SigD (reifyName op) ty) }
455 ------------------------------
456 reifyType :: TypeRep.Type -> TcM TH.Type
457 reifyType (TyVarTy tv) = return (TH.VarT (reifyName tv))
458 reifyType (TyConApp tc tys) = reify_tc_app (reifyName tc) tys
459 reifyType (NewTcApp tc tys) = reify_tc_app (reifyName tc) tys
460 reifyType (NoteTy _ ty) = reifyType ty
461 reifyType (AppTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (r1 `TH.AppT` r2) }
462 reifyType (FunTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (TH.ArrowT `TH.AppT` r1 `TH.AppT` r2) }
463 reifyType ty@(ForAllTy _ _) = do { cxt' <- reifyCxt cxt;
464 ; tau' <- reifyType tau
465 ; return (TH.ForallT (reifyTyVars tvs) cxt' tau') }
467 (tvs, cxt, tau) = tcSplitSigmaTy ty
468 reifyTypes = mapM reifyType
469 reifyCxt = mapM reifyPred
471 reifyTyVars :: [TyVar] -> [TH.Name]
472 reifyTyVars = map reifyName
474 reify_tc_app :: TH.Name -> [TypeRep.Type] -> TcM TH.Type
475 reify_tc_app tc tys = do { tys' <- reifyTypes tys
476 ; return (foldl TH.AppT (TH.ConT tc) tys') }
478 reifyPred :: TypeRep.PredType -> TcM TH.Type
479 reifyPred (ClassP cls tys) = reify_tc_app (reifyName cls) tys
480 reifyPred p@(IParam _ _) = noTH SLIT("implicit parameters") (ppr p)
483 ------------------------------
484 reifyName :: NamedThing n => n -> TH.Name
486 | isExternalName name = mk_varg mod occ_str
487 | otherwise = TH.mkNameU occ_str (getKey (getUnique name))
490 mod = moduleUserString (nameModule name)
491 occ_str = occNameUserString occ
492 occ = nameOccName name
493 mk_varg | OccName.isDataOcc occ = TH.mkNameG_d
494 | OccName.isVarOcc occ = TH.mkNameG_v
495 | OccName.isTcOcc occ = TH.mkNameG_tc
496 | otherwise = pprPanic "reifyName" (ppr name)
498 ------------------------------
499 reifyFixity :: Name -> TcM TH.Fixity
501 = do { fix <- lookupFixityRn name
502 ; return (conv_fix fix) }
504 conv_fix (BasicTypes.Fixity i d) = TH.Fixity i (conv_dir d)
505 conv_dir BasicTypes.InfixR = TH.InfixR
506 conv_dir BasicTypes.InfixL = TH.InfixL
507 conv_dir BasicTypes.InfixN = TH.InfixN
509 reifyStrict :: BasicTypes.StrictnessMark -> TH.Strict
510 reifyStrict MarkedStrict = TH.IsStrict
511 reifyStrict MarkedUnboxed = TH.IsStrict
512 reifyStrict NotMarkedStrict = TH.NotStrict
514 ------------------------------
515 noTH :: LitString -> SDoc -> TcM a
516 noTH s d = failWithTc (hsep [ptext SLIT("Can't represent") <+> ptext s <+>
517 ptext SLIT("in Template Haskell:"),