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_`
209 rnExpr expr2 `thenM` \ (exp3, fvs) ->
211 tcMonoExpr exp3 res_ty
214 tcTopSpliceExpr :: RenamedHsExpr -> TcType -> TcM TypecheckedHsExpr
215 -- Type check an expression that is the body of a top-level splice
216 -- (the caller will compile and run it)
217 tcTopSpliceExpr expr meta_ty
218 = checkNoErrs $ -- checkNoErrs: must not try to run the thing
219 -- if the type checker fails!
221 setStage topSpliceStage $
223 -- Typecheck the expression
224 getLIE (tcCheckRho expr meta_ty) `thenM` \ (expr', lie) ->
226 -- Solve the constraints
227 tcSimplifyTop lie `thenM` \ const_binds ->
230 zonkTopExpr (mkHsLet const_binds expr')
234 %************************************************************************
236 \subsection{Splicing an expression}
238 %************************************************************************
241 -- Always at top level
243 = tcMetaTy decTyConName `thenM` \ meta_dec_ty ->
244 tcMetaTy qTyConName `thenM` \ meta_q_ty ->
246 list_q = mkAppTy meta_q_ty (mkListTy meta_dec_ty)
248 tcTopSpliceExpr expr list_q `thenM` \ zonked_q_expr ->
250 -- Run the expression
251 traceTc (text "About to run" <+> ppr zonked_q_expr) `thenM_`
252 runMetaD zonked_q_expr `thenM` \ simple_expr ->
253 -- simple_expr :: [TH.Dec]
254 -- decls :: [RdrNameHsDecl]
255 handleErrors (convertToHsDecls simple_expr) `thenM` \ decls ->
256 traceTc (text "Got result" <+> vcat (map ppr decls)) `thenM_`
257 showSplice "declarations"
258 zonked_q_expr (vcat (map ppr decls)) `thenM_`
261 where handleErrors :: [Either a Message] -> TcM [a]
262 handleErrors [] = return []
263 handleErrors (Left x:xs) = liftM (x:) (handleErrors xs)
264 handleErrors (Right m:xs) = do addErrTc m
269 %************************************************************************
271 \subsection{Running an expression}
273 %************************************************************************
276 runMetaE :: TypecheckedHsExpr -- Of type (Q Exp)
277 -> TcM TH.Exp -- Of type Exp
278 runMetaE e = runMeta e
280 runMetaD :: TypecheckedHsExpr -- Of type Q [Dec]
281 -> TcM [TH.Dec] -- Of type [Dec]
282 runMetaD e = runMeta e
284 runMeta :: TypecheckedHsExpr -- Of type X
285 -> TcM t -- Of type t
287 = do { hsc_env <- getTopEnv
288 ; tcg_env <- getGblEnv
289 ; this_mod <- getModule
290 ; let type_env = tcg_type_env tcg_env
291 rdr_env = tcg_rdr_env tcg_env
292 -- Wrap the compile-and-run in an exception-catcher
293 -- Compiling might fail if linking fails
294 -- Running might fail if it throws an exception
295 ; either_tval <- tryM $ do
297 hval <- ioToTcRn (HscMain.compileExpr
299 rdr_env type_env expr)
300 -- Coerce it to Q t, and run it
301 ; TH.runQ (unsafeCoerce# hval) }
303 ; case either_tval of
304 Left exn -> failWithTc (vcat [text "Exception when trying to run compile-time code:",
305 nest 4 (vcat [text "Code:" <+> ppr expr,
306 text ("Exn: " ++ Panic.showException exn)])])
307 Right v -> returnM v }
310 To call runQ in the Tc monad, we need to make TcM an instance of Quasi:
313 instance TH.Quasi (IOEnv (Env TcGblEnv TcLclEnv)) where
314 qNewName s = do { u <- newUnique
316 ; return (TH.mkNameU s i) }
318 qReport True msg = addErr (text msg)
319 qReport False msg = addReport (text msg)
321 qCurrentModule = do { m <- getModule; return (moduleUserString m) }
325 qRunIO io = ioToTcRn io
329 %************************************************************************
331 \subsection{Errors and contexts}
333 %************************************************************************
336 showSplice :: String -> TypecheckedHsExpr -> SDoc -> TcM ()
337 showSplice what before after
338 = getSrcLocM `thenM` \ loc ->
339 traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what,
340 nest 2 (sep [nest 2 (ppr before),
345 = ptext SLIT("Illegal bracket at level") <+> ppr level
348 = ptext SLIT("Illegal splice at level") <+> ppr level
354 %************************************************************************
358 %************************************************************************
362 reify :: TH.Name -> TcM TH.Info
363 reify (TH.Name occ (TH.NameG th_ns mod))
364 = do { name <- lookupOrig (mkModuleName (TH.modString mod))
365 (OccName.mkOccName ghc_ns (TH.occString occ))
366 ; thing <- tcLookup name
370 ghc_ns = case th_ns of
371 TH.DataName -> dataName
372 TH.TcClsName -> tcClsName
373 TH.VarName -> varName
375 ------------------------------
376 reifyThing :: TcTyThing -> TcM TH.Info
377 -- The only reason this is monadic is for error reporting,
378 -- which in turn is mainly for the case when TH can't express
379 -- some random GHC extension
381 reifyThing (AGlobal (AnId id))
382 = do { ty <- reifyType (idType id)
383 ; fix <- reifyFixity (idName id)
384 ; let v = reifyName id
385 ; case globalIdDetails id of
386 ClassOpId cls -> return (TH.ClassOpI v ty (reifyName cls) fix)
387 other -> return (TH.VarI v ty Nothing fix)
390 reifyThing (AGlobal (ATyCon tc)) = do { dec <- reifyTyCon tc; return (TH.TyConI dec) }
391 reifyThing (AGlobal (AClass cls)) = do { dec <- reifyClass cls; return (TH.ClassI dec) }
392 reifyThing (AGlobal (ADataCon dc))
393 = do { let name = dataConName dc
394 ; ty <- reifyType (idType (dataConWrapId dc))
395 ; fix <- reifyFixity name
396 ; return (TH.DataConI (reifyName name) ty (reifyName (dataConTyCon dc)) fix) }
398 reifyThing (ATcId id _ _)
399 = do { ty1 <- zonkTcType (idType id) -- Make use of all the info we have, even
400 -- though it may be incomplete
401 ; ty2 <- reifyType ty1
402 ; fix <- reifyFixity (idName id)
403 ; return (TH.VarI (reifyName id) ty2 Nothing fix) }
405 reifyThing (ATyVar tv)
406 = do { ty1 <- zonkTcTyVar tv
407 ; ty2 <- reifyType ty1
408 ; return (TH.TyVarI (reifyName tv) ty2) }
410 ------------------------------
411 reifyTyCon :: TyCon -> TcM TH.Dec
414 = do { let (tvs, rhs) = getSynTyConDefn tc
415 ; rhs' <- reifyType rhs
416 ; return (TH.TySynD (reifyName tc) (reifyTyVars tvs) rhs') }
419 = do { cxt <- reifyCxt (tyConTheta tc)
420 ; con <- reifyDataCon (head (tyConDataCons tc))
421 ; return (TH.NewtypeD cxt (reifyName tc) (reifyTyVars (tyConTyVars tc))
422 con [{- Don't know about deriving -}]) }
424 | otherwise -- Algebraic
425 = do { cxt <- reifyCxt (tyConTheta tc)
426 ; cons <- mapM reifyDataCon (tyConDataCons tc)
427 ; return (TH.DataD cxt (reifyName tc) (reifyTyVars (tyConTyVars tc))
428 cons [{- Don't know about deriving -}]) }
430 reifyDataCon :: DataCon -> TcM TH.Con
432 = do { arg_tys <- reifyTypes (dataConOrigArgTys dc)
433 ; let stricts = map reifyStrict (dataConStrictMarks dc)
434 fields = dataConFieldLabels dc
435 ; if null fields then
436 return (TH.NormalC (reifyName dc) (stricts `zip` arg_tys))
438 return (TH.RecC (reifyName dc) (zip3 (map reifyName fields) stricts arg_tys)) }
439 -- NB: we don't remember whether the constructor was declared in an infix way
441 ------------------------------
442 reifyClass :: Class -> TcM TH.Dec
444 = do { cxt <- reifyCxt theta
445 ; ops <- mapM reify_op op_stuff
446 ; return (TH.ClassD cxt (reifyName cls) (reifyTyVars tvs) ops) }
448 (tvs, theta, _, op_stuff) = classBigSig cls
449 reify_op (op, _) = do { ty <- reifyType (idType op)
450 ; return (TH.SigD (reifyName op) ty) }
452 ------------------------------
453 reifyType :: TypeRep.Type -> TcM TH.Type
454 reifyType (TyVarTy tv) = return (TH.VarT (reifyName tv))
455 reifyType (TyConApp tc tys) = reify_tc_app (reifyName tc) tys
456 reifyType (NewTcApp tc tys) = reify_tc_app (reifyName tc) tys
457 reifyType (NoteTy _ ty) = reifyType ty
458 reifyType (AppTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (r1 `TH.AppT` r2) }
459 reifyType (FunTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (TH.ArrowT `TH.AppT` r1 `TH.AppT` r2) }
460 reifyType ty@(ForAllTy _ _) = do { cxt' <- reifyCxt cxt;
461 ; tau' <- reifyType tau
462 ; return (TH.ForallT (reifyTyVars tvs) cxt' tau') }
464 (tvs, cxt, tau) = tcSplitSigmaTy ty
465 reifyTypes = mapM reifyType
466 reifyCxt = mapM reifyPred
468 reifyTyVars :: [TyVar] -> [TH.Name]
469 reifyTyVars = map reifyName
471 reify_tc_app :: TH.Name -> [TypeRep.Type] -> TcM TH.Type
472 reify_tc_app tc tys = do { tys' <- reifyTypes tys
473 ; return (foldl TH.AppT (TH.ConT tc) tys') }
475 reifyPred :: TypeRep.PredType -> TcM TH.Type
476 reifyPred (ClassP cls tys) = reify_tc_app (reifyName cls) tys
477 reifyPred p@(IParam _ _) = noTH SLIT("implicit parameters") (ppr p)
480 ------------------------------
481 reifyName :: NamedThing n => n -> TH.Name
483 | isExternalName name = mk_varg mod occ_str
484 | otherwise = TH.mkNameU occ_str (getKey (getUnique name))
487 mod = moduleUserString (nameModule name)
488 occ_str = occNameUserString occ
489 occ = nameOccName name
490 mk_varg | OccName.isDataOcc occ = TH.mkNameG_d
491 | OccName.isVarOcc occ = TH.mkNameG_v
492 | OccName.isTcOcc occ = TH.mkNameG_tc
493 | otherwise = pprPanic "reifyName" (ppr name)
495 ------------------------------
496 reifyFixity :: Name -> TcM TH.Fixity
498 = do { fix <- lookupFixityRn name
499 ; return (conv_fix fix) }
501 conv_fix (BasicTypes.Fixity i d) = TH.Fixity i (conv_dir d)
502 conv_dir BasicTypes.InfixR = TH.InfixR
503 conv_dir BasicTypes.InfixL = TH.InfixL
504 conv_dir BasicTypes.InfixN = TH.InfixN
506 reifyStrict :: BasicTypes.StrictnessMark -> TH.Strict
507 reifyStrict MarkedStrict = TH.IsStrict
508 reifyStrict MarkedUnboxed = TH.IsStrict
509 reifyStrict NotMarkedStrict = TH.NotStrict
511 ------------------------------
512 noTH :: LitString -> SDoc -> TcM a
513 noTH s d = failWithTc (hsep [ptext SLIT("Can't represent") <+> ptext s <+>
514 ptext SLIT("in Template Haskell:"),