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(..), LHsExpr, LHsDecl )
21 import Convert ( convertToHsExpr, convertToHsDecls )
22 import RnExpr ( rnLExpr )
23 import RnEnv ( lookupFixityRn )
24 import TcExpr ( tcCheckRho, tcMonoExpr )
25 import TcHsSyn ( mkHsLet, zonkTopLExpr )
26 import TcSimplify ( tcSimplifyTop, tcSimplifyBracket )
27 import TcUnify ( Expected, zapExpectedTo, zapExpectedType )
28 import TcType ( TcType, openTypeKind, mkAppTy, tcSplitSigmaTy )
29 import TcEnv ( spliceOK, tcMetaTy, bracketOK, tcLookup )
30 import TcMType ( newTyVarTy, UserTypeCtxt(ExprSigCtxt), zonkTcType, zonkTcTyVar )
31 import TcHsType ( tcHsSigType )
32 import TypeRep ( Type(..), PredType(..), TyThing(..) ) -- For reification
33 import Name ( Name, NamedThing(..), nameOccName, nameModule, isExternalName )
35 import Var ( Id, TyVar, idType )
36 import RdrName ( RdrName )
37 import Module ( moduleUserString, mkModuleName )
39 import IfaceEnv ( lookupOrig )
41 import Class ( Class, classBigSig )
42 import TyCon ( TyCon, tyConTheta, tyConTyVars, getSynTyConDefn, isSynTyCon, isNewTyCon, tyConDataCons )
43 import DataCon ( DataCon, dataConTyCon, dataConOrigArgTys, dataConStrictMarks,
44 dataConName, dataConFieldLabels, dataConWrapId )
45 import Id ( idName, globalIdDetails )
46 import IdInfo ( GlobalIdDetails(..) )
47 import TysWiredIn ( mkListTy )
48 import DsMeta ( expQTyConName, typeQTyConName, decTyConName, qTyConName, nameTyConName )
49 import ErrUtils ( Message )
50 import SrcLoc ( noLoc, unLoc )
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 FastString ( LitString )
58 import FastTypes ( iBox )
60 import GHC.Base ( unsafeCoerce#, Int(..) ) -- Should have a better home in the module hierarchy
61 import Monad ( liftM )
65 %************************************************************************
67 \subsection{Main interface + stubs for the non-GHCI case
69 %************************************************************************
72 tcSpliceDecls :: LHsExpr Name -> TcM [LHsDecl RdrName]
80 tcSpliceExpr n e ty = pprPanic "Cant do tcSpliceExpr without GHCi" (ppr e)
81 tcSpliceDecls e = pprPanic "Cant do tcSpliceDecls without GHCi" (ppr e)
85 %************************************************************************
87 \subsection{Quoting an expression}
89 %************************************************************************
92 tcBracket :: HsBracket Name -> Expected TcType -> TcM (LHsExpr Id)
93 tcBracket brack res_ty
94 = getStage `thenM` \ level ->
95 case bracketOK level of {
96 Nothing -> failWithTc (illegalBracket level) ;
99 -- Typecheck expr to make sure it is valid,
100 -- but throw away the results. We'll type check
101 -- it again when we actually use it.
102 newMutVar [] `thenM` \ pending_splices ->
103 getLIEVar `thenM` \ lie_var ->
105 setStage (Brack next_level pending_splices lie_var) (
106 getLIE (tc_bracket brack)
107 ) `thenM` \ (meta_ty, lie) ->
108 tcSimplifyBracket lie `thenM_`
110 -- Make the expected type have the right shape
111 zapExpectedTo res_ty meta_ty `thenM_`
113 -- Return the original expression, not the type-decorated one
114 readMutVar pending_splices `thenM` \ pendings ->
115 returnM (noLoc (HsBracketOut brack pendings))
118 tc_bracket :: HsBracket Name -> TcM TcType
120 = tcMetaTy nameTyConName
121 -- Result type is Var (not Q-monadic)
123 tc_bracket (ExpBr expr)
124 = newTyVarTy openTypeKind `thenM` \ any_ty ->
125 tcCheckRho expr any_ty `thenM_`
126 tcMetaTy expQTyConName
127 -- Result type is Expr (= Q Exp)
129 tc_bracket (TypBr typ)
130 = tcHsSigType ExprSigCtxt typ `thenM_`
131 tcMetaTy typeQTyConName
132 -- Result type is Type (= Q Typ)
134 tc_bracket (DecBr decls)
135 = tcTopSrcDecls decls `thenM_`
136 -- Typecheck the declarations, dicarding the result
137 -- We'll get all that stuff later, when we splice it in
139 tcMetaTy decTyConName `thenM` \ decl_ty ->
140 tcMetaTy qTyConName `thenM` \ q_ty ->
141 returnM (mkAppTy q_ty (mkListTy decl_ty))
142 -- Result type is Q [Dec]
146 %************************************************************************
148 \subsection{Splicing an expression}
150 %************************************************************************
153 tcSpliceExpr name expr res_ty
154 = getStage `thenM` \ level ->
155 case spliceOK level of {
156 Nothing -> failWithTc (illegalSplice level) ;
160 Comp -> do { e <- tcTopSplice expr res_ty ;
162 Brack _ ps_var lie_var ->
164 -- A splice inside brackets
165 -- NB: ignore res_ty, apart from zapping it to a mono-type
166 -- e.g. [| reverse $(h 4) |]
167 -- Here (h 4) :: Q Exp
168 -- but $(h 4) :: forall a.a i.e. anything!
170 zapExpectedType res_ty `thenM_`
171 tcMetaTy expQTyConName `thenM` \ meta_exp_ty ->
172 setStage (Splice next_level) (
174 tcCheckRho expr meta_exp_ty
177 -- Write the pending splice into the bucket
178 readMutVar ps_var `thenM` \ ps ->
179 writeMutVar ps_var ((name,expr') : ps) `thenM_`
181 returnM (panic "tcSpliceExpr") -- The returned expression is ignored
184 -- tcTopSplice used to have this:
185 -- Note that we do not decrement the level (to -1) before
186 -- typechecking the expression. For example:
187 -- f x = $( ...$(g 3) ... )
188 -- The recursive call to tcMonoExpr will simply expand the
189 -- inner escape before dealing with the outer one
191 tcTopSplice :: LHsExpr Name -> Expected TcType -> TcM (LHsExpr Id)
192 tcTopSplice expr res_ty
193 = tcMetaTy expQTyConName `thenM` \ meta_exp_ty ->
195 -- Typecheck the expression
196 tcTopSpliceExpr expr meta_exp_ty `thenM` \ zonked_q_expr ->
198 -- Run the expression
199 traceTc (text "About to run" <+> ppr zonked_q_expr) `thenM_`
200 runMetaE zonked_q_expr `thenM` \ simple_expr ->
203 -- simple_expr :: TH.Exp
205 expr2 :: LHsExpr RdrName
206 expr2 = convertToHsExpr simple_expr
208 traceTc (text "Got result" <+> ppr expr2) `thenM_`
210 showSplice "expression"
211 zonked_q_expr (ppr expr2) `thenM_`
213 -- Rename it, but bale out if there are errors
214 -- otherwise the type checker just gives more spurious errors
215 checkNoErrs (rnLExpr expr2) `thenM` \ (exp3, fvs) ->
217 tcMonoExpr exp3 res_ty
220 tcTopSpliceExpr :: LHsExpr Name -> TcType -> TcM (LHsExpr Id)
221 -- Type check an expression that is the body of a top-level splice
222 -- (the caller will compile and run it)
223 tcTopSpliceExpr expr meta_ty
224 = checkNoErrs $ -- checkNoErrs: must not try to run the thing
225 -- if the type checker fails!
227 setStage topSpliceStage $
229 -- Typecheck the expression
230 getLIE (tcCheckRho expr meta_ty) `thenM` \ (expr', lie) ->
232 -- Solve the constraints
233 tcSimplifyTop lie `thenM` \ const_binds ->
236 zonkTopLExpr (mkHsLet const_binds expr')
240 %************************************************************************
242 \subsection{Splicing an expression}
244 %************************************************************************
247 -- Always at top level
249 = tcMetaTy decTyConName `thenM` \ meta_dec_ty ->
250 tcMetaTy qTyConName `thenM` \ meta_q_ty ->
252 list_q = mkAppTy meta_q_ty (mkListTy meta_dec_ty)
254 tcTopSpliceExpr expr list_q `thenM` \ zonked_q_expr ->
256 -- Run the expression
257 traceTc (text "About to run" <+> ppr zonked_q_expr) `thenM_`
258 runMetaD zonked_q_expr `thenM` \ simple_expr ->
259 -- simple_expr :: [TH.Dec]
260 -- decls :: [RdrNameHsDecl]
261 handleErrors (convertToHsDecls simple_expr) `thenM` \ decls ->
262 traceTc (text "Got result" <+> vcat (map ppr decls)) `thenM_`
263 showSplice "declarations"
264 zonked_q_expr (vcat (map ppr decls)) `thenM_`
267 where handleErrors :: [Either a Message] -> TcM [a]
268 handleErrors [] = return []
269 handleErrors (Left x:xs) = liftM (x:) (handleErrors xs)
270 handleErrors (Right m:xs) = do addErrTc m
275 %************************************************************************
277 \subsection{Running an expression}
279 %************************************************************************
282 runMetaE :: LHsExpr Id -- Of type (Q Exp)
283 -> TcM TH.Exp -- Of type Exp
284 runMetaE e = runMeta e
286 runMetaD :: LHsExpr Id -- Of type Q [Dec]
287 -> TcM [TH.Dec] -- Of type [Dec]
288 runMetaD e = runMeta e
290 runMeta :: LHsExpr Id -- Of type X
291 -> TcM t -- Of type t
293 = do { hsc_env <- getTopEnv
294 ; tcg_env <- getGblEnv
295 ; this_mod <- getModule
296 ; let type_env = tcg_type_env tcg_env
297 rdr_env = tcg_rdr_env tcg_env
298 -- Wrap the compile-and-run in an exception-catcher
299 -- Compiling might fail if linking fails
300 -- Running might fail if it throws an exception
301 ; either_tval <- tryM $ do
303 hval <- ioToTcRn (HscMain.compileExpr
305 rdr_env type_env expr)
306 -- Coerce it to Q t, and run it
307 ; TH.runQ (unsafeCoerce# hval) }
309 ; case either_tval of
310 Left exn -> failWithTc (vcat [text "Exception when trying to run compile-time code:",
311 nest 4 (vcat [text "Code:" <+> ppr expr,
312 text ("Exn: " ++ Panic.showException exn)])])
313 Right v -> returnM v }
316 To call runQ in the Tc monad, we need to make TcM an instance of Quasi:
319 instance TH.Quasi (IOEnv (Env TcGblEnv TcLclEnv)) where
320 qNewName s = do { u <- newUnique
322 ; return (TH.mkNameU s i) }
324 qReport True msg = addErr (text msg)
325 qReport False msg = addReport (text msg)
327 qCurrentModule = do { m <- getModule; return (moduleUserString m) }
331 qRunIO io = ioToTcRn io
335 %************************************************************************
337 \subsection{Errors and contexts}
339 %************************************************************************
342 showSplice :: String -> LHsExpr Id -> SDoc -> TcM ()
343 showSplice what before after
344 = getSrcSpanM `thenM` \ loc ->
345 traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what,
346 nest 2 (sep [nest 2 (ppr before),
351 = ptext SLIT("Illegal bracket at level") <+> ppr level
354 = ptext SLIT("Illegal splice at level") <+> ppr level
360 %************************************************************************
364 %************************************************************************
368 reify :: TH.Name -> TcM TH.Info
369 reify (TH.Name occ (TH.NameG th_ns mod))
370 = do { name <- lookupOrig (mkModuleName (TH.modString mod))
371 (OccName.mkOccName ghc_ns (TH.occString occ))
372 ; thing <- tcLookup name
376 ghc_ns = case th_ns of
377 TH.DataName -> dataName
378 TH.TcClsName -> tcClsName
379 TH.VarName -> varName
381 ------------------------------
382 reifyThing :: TcTyThing -> TcM TH.Info
383 -- The only reason this is monadic is for error reporting,
384 -- which in turn is mainly for the case when TH can't express
385 -- some random GHC extension
387 reifyThing (AGlobal (AnId id))
388 = do { ty <- reifyType (idType id)
389 ; fix <- reifyFixity (idName id)
390 ; let v = reifyName id
391 ; case globalIdDetails id of
392 ClassOpId cls -> return (TH.ClassOpI v ty (reifyName cls) fix)
393 other -> return (TH.VarI v ty Nothing fix)
396 reifyThing (AGlobal (ATyCon tc)) = do { dec <- reifyTyCon tc; return (TH.TyConI dec) }
397 reifyThing (AGlobal (AClass cls)) = do { dec <- reifyClass cls; return (TH.ClassI dec) }
398 reifyThing (AGlobal (ADataCon dc))
399 = do { let name = dataConName dc
400 ; ty <- reifyType (idType (dataConWrapId dc))
401 ; fix <- reifyFixity name
402 ; return (TH.DataConI (reifyName name) ty (reifyName (dataConTyCon dc)) fix) }
404 reifyThing (ATcId id _ _)
405 = do { ty1 <- zonkTcType (idType id) -- Make use of all the info we have, even
406 -- though it may be incomplete
407 ; ty2 <- reifyType ty1
408 ; fix <- reifyFixity (idName id)
409 ; return (TH.VarI (reifyName id) ty2 Nothing fix) }
411 reifyThing (ATyVar tv)
412 = do { ty1 <- zonkTcTyVar tv
413 ; ty2 <- reifyType ty1
414 ; return (TH.TyVarI (reifyName tv) ty2) }
416 ------------------------------
417 reifyTyCon :: TyCon -> TcM TH.Dec
420 = do { let (tvs, rhs) = getSynTyConDefn tc
421 ; rhs' <- reifyType rhs
422 ; return (TH.TySynD (reifyName tc) (reifyTyVars tvs) rhs') }
425 = do { cxt <- reifyCxt (tyConTheta tc)
426 ; con <- reifyDataCon (head (tyConDataCons tc))
427 ; return (TH.NewtypeD cxt (reifyName tc) (reifyTyVars (tyConTyVars tc))
428 con [{- Don't know about deriving -}]) }
430 | otherwise -- Algebraic
431 = do { cxt <- reifyCxt (tyConTheta tc)
432 ; cons <- mapM reifyDataCon (tyConDataCons tc)
433 ; return (TH.DataD cxt (reifyName tc) (reifyTyVars (tyConTyVars tc))
434 cons [{- Don't know about deriving -}]) }
436 reifyDataCon :: DataCon -> TcM TH.Con
438 = do { arg_tys <- reifyTypes (dataConOrigArgTys dc)
439 ; let stricts = map reifyStrict (dataConStrictMarks dc)
440 fields = dataConFieldLabels dc
441 ; if null fields then
442 return (TH.NormalC (reifyName dc) (stricts `zip` arg_tys))
444 return (TH.RecC (reifyName dc) (zip3 (map reifyName fields) stricts arg_tys)) }
445 -- NB: we don't remember whether the constructor was declared in an infix way
447 ------------------------------
448 reifyClass :: Class -> TcM TH.Dec
450 = do { cxt <- reifyCxt theta
451 ; ops <- mapM reify_op op_stuff
452 ; return (TH.ClassD cxt (reifyName cls) (reifyTyVars tvs) ops) }
454 (tvs, theta, _, op_stuff) = classBigSig cls
455 reify_op (op, _) = do { ty <- reifyType (idType op)
456 ; return (TH.SigD (reifyName op) ty) }
458 ------------------------------
459 reifyType :: TypeRep.Type -> TcM TH.Type
460 reifyType (TyVarTy tv) = return (TH.VarT (reifyName tv))
461 reifyType (TyConApp tc tys) = reify_tc_app (reifyName tc) tys
462 reifyType (NewTcApp tc tys) = reify_tc_app (reifyName tc) tys
463 reifyType (NoteTy _ ty) = reifyType ty
464 reifyType (AppTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (r1 `TH.AppT` r2) }
465 reifyType (FunTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (TH.ArrowT `TH.AppT` r1 `TH.AppT` r2) }
466 reifyType ty@(ForAllTy _ _) = do { cxt' <- reifyCxt cxt;
467 ; tau' <- reifyType tau
468 ; return (TH.ForallT (reifyTyVars tvs) cxt' tau') }
470 (tvs, cxt, tau) = tcSplitSigmaTy ty
471 reifyTypes = mapM reifyType
472 reifyCxt = mapM reifyPred
474 reifyTyVars :: [TyVar] -> [TH.Name]
475 reifyTyVars = map reifyName
477 reify_tc_app :: TH.Name -> [TypeRep.Type] -> TcM TH.Type
478 reify_tc_app tc tys = do { tys' <- reifyTypes tys
479 ; return (foldl TH.AppT (TH.ConT tc) tys') }
481 reifyPred :: TypeRep.PredType -> TcM TH.Type
482 reifyPred (ClassP cls tys) = reify_tc_app (reifyName cls) tys
483 reifyPred p@(IParam _ _) = noTH SLIT("implicit parameters") (ppr p)
486 ------------------------------
487 reifyName :: NamedThing n => n -> TH.Name
489 | isExternalName name = mk_varg mod occ_str
490 | otherwise = TH.mkNameU occ_str (getKey (getUnique name))
493 mod = moduleUserString (nameModule name)
494 occ_str = occNameUserString occ
495 occ = nameOccName name
496 mk_varg | OccName.isDataOcc occ = TH.mkNameG_d
497 | OccName.isVarOcc occ = TH.mkNameG_v
498 | OccName.isTcOcc occ = TH.mkNameG_tc
499 | otherwise = pprPanic "reifyName" (ppr name)
501 ------------------------------
502 reifyFixity :: Name -> TcM TH.Fixity
504 = do { fix <- lookupFixityRn name
505 ; return (conv_fix fix) }
507 conv_fix (BasicTypes.Fixity i d) = TH.Fixity i (conv_dir d)
508 conv_dir BasicTypes.InfixR = TH.InfixR
509 conv_dir BasicTypes.InfixL = TH.InfixL
510 conv_dir BasicTypes.InfixN = TH.InfixN
512 reifyStrict :: BasicTypes.StrictnessMark -> TH.Strict
513 reifyStrict MarkedStrict = TH.IsStrict
514 reifyStrict MarkedUnboxed = TH.IsStrict
515 reifyStrict NotMarkedStrict = TH.NotStrict
517 ------------------------------
518 noTH :: LitString -> SDoc -> TcM a
519 noTH s d = failWithTc (hsep [ptext SLIT("Can't represent") <+> ptext s <+>
520 ptext SLIT("in Template Haskell:"),