f1e8c5644d48641613ab0a42efcda7db06362b2b
[ghc-hetmet.git] / compiler / typecheck / TcSplice.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcSplice]{Template Haskell splices}
5
6 \begin{code}
7 module TcSplice( tcSpliceExpr, tcSpliceDecls, tcBracket ) where
8
9 #include "HsVersions.h"
10
11 import HscMain          ( compileExpr )
12 import TcRnDriver       ( tcTopSrcDecls )
13         -- These imports are the reason that TcSplice 
14         -- is very high up the module hierarchy
15
16 import qualified Language.Haskell.TH as TH
17 -- THSyntax gives access to internal functions and data types
18 import qualified Language.Haskell.TH.Syntax as TH
19
20 import HsSyn            ( HsBracket(..), HsExpr(..), HsSplice(..), LHsExpr, LHsDecl, 
21                           HsType, LHsType )
22 import Convert          ( convertToHsExpr, convertToHsDecls, convertToHsType, thRdrName )
23 import RnExpr           ( rnLExpr )
24 import RnEnv            ( lookupFixityRn, lookupSrcOcc_maybe, lookupImportedName )
25 import RdrName          ( RdrName, lookupLocalRdrEnv, isSrcRdrName )
26 import RnTypes          ( rnLHsType )
27 import TcExpr           ( tcMonoExpr )
28 import TcHsSyn          ( mkHsDictLet, zonkTopLExpr )
29 import TcSimplify       ( tcSimplifyTop, tcSimplifyBracket )
30 import TcUnify          ( boxyUnify, unBox )
31 import TcType           ( TcType, TcKind, BoxyRhoType, liftedTypeKind, mkAppTy, tcSplitSigmaTy )
32 import TcEnv            ( spliceOK, tcMetaTy, bracketOK )
33 import TcMType          ( newFlexiTyVarTy, newKindVar, UserTypeCtxt(ExprSigCtxt), zonkTcType )
34 import TcHsType         ( tcHsSigType, kcHsType )
35 import TcIface          ( tcImportDecl )
36 import TypeRep          ( Type(..), PredType(..), TyThing(..) ) -- For reification
37 import PrelNames        ( thFAKE )
38 import Name             ( Name, NamedThing(..), nameOccName, nameModule, isExternalName, 
39                           nameIsLocalOrFrom )
40 import NameEnv          ( lookupNameEnv )
41 import HscTypes         ( lookupType, ExternalPackageState(..), emptyModDetails )
42 import OccName
43 import Var              ( Id, TyVar, idType )
44 import Module           ( moduleName, moduleNameString, modulePackageId )
45 import TcRnMonad
46 import IfaceEnv         ( lookupOrig )
47 import Class            ( Class, classExtraBigSig )
48 import TyCon            ( TyCon, tyConTyVars, synTyConDefn, 
49                           isSynTyCon, isNewTyCon, tyConDataCons, isPrimTyCon, isFunTyCon,
50                           tyConArity, tyConStupidTheta, isUnLiftedTyCon )
51 import DataCon          ( DataCon, dataConTyCon, dataConOrigArgTys, dataConStrictMarks, 
52                           dataConName, dataConFieldLabels, dataConWrapId, dataConIsInfix, 
53                           isVanillaDataCon )
54 import Id               ( idName, globalIdDetails )
55 import IdInfo           ( GlobalIdDetails(..) )
56 import TysWiredIn       ( mkListTy )
57 import DsMeta           ( expQTyConName, typeQTyConName, decTyConName, qTyConName, nameTyConName )
58 import ErrUtils         ( Message )
59 import SrcLoc           ( SrcSpan, noLoc, unLoc, getLoc )
60 import Outputable
61 import Unique           ( Unique, Uniquable(..), getKey, mkUniqueGrimily )
62 import PackageConfig    ( packageIdString )
63 import BasicTypes       ( StrictnessMark(..), Fixity(..), FixityDirection(..) )
64 import Panic            ( showException )
65 import FastString       ( LitString )
66
67 import GHC.Base         ( unsafeCoerce#, Int#, Int(..) )        -- Should have a better home in the module hierarchy
68 import Monad            ( liftM )
69
70 #ifdef GHCI
71 import FastString       ( mkFastString )
72 #endif
73 \end{code}
74
75
76 %************************************************************************
77 %*                                                                      *
78 \subsection{Main interface + stubs for the non-GHCI case
79 %*                                                                      *
80 %************************************************************************
81
82 \begin{code}
83 tcSpliceDecls :: LHsExpr Name -> TcM [LHsDecl RdrName]
84 tcSpliceExpr  :: HsSplice Name -> BoxyRhoType -> TcM (HsExpr TcId)
85 kcSpliceType  :: HsSplice Name -> TcM (HsType Name, TcKind)
86
87 #ifndef GHCI
88 tcSpliceExpr n e ty = pprPanic "Cant do tcSpliceExpr without GHCi" (ppr e)
89 tcSpliceDecls e     = pprPanic "Cant do tcSpliceDecls without GHCi" (ppr e)
90 #else
91 \end{code}
92
93 %************************************************************************
94 %*                                                                      *
95 \subsection{Quoting an expression}
96 %*                                                                      *
97 %************************************************************************
98
99 \begin{code}
100 tcBracket :: HsBracket Name -> BoxyRhoType -> TcM (LHsExpr TcId)
101 tcBracket brack res_ty
102   = getStage                            `thenM` \ level ->
103     case bracketOK level of {
104         Nothing         -> failWithTc (illegalBracket level) ;
105         Just next_level ->
106
107         -- Typecheck expr to make sure it is valid,
108         -- but throw away the results.  We'll type check
109         -- it again when we actually use it.
110     recordThUse                         `thenM_`
111     newMutVar []                        `thenM` \ pending_splices ->
112     getLIEVar                           `thenM` \ lie_var ->
113
114     setStage (Brack next_level pending_splices lie_var) (
115         getLIE (tc_bracket brack)
116     )                                   `thenM` \ (meta_ty, lie) ->
117     tcSimplifyBracket lie               `thenM_`  
118
119         -- Make the expected type have the right shape
120     boxyUnify meta_ty res_ty            `thenM_`
121
122         -- Return the original expression, not the type-decorated one
123     readMutVar pending_splices          `thenM` \ pendings ->
124     returnM (noLoc (HsBracketOut brack pendings))
125     }
126
127 tc_bracket :: HsBracket Name -> TcM TcType
128 tc_bracket (VarBr v) 
129   = tcMetaTy nameTyConName      -- Result type is Var (not Q-monadic)
130
131 tc_bracket (ExpBr expr) 
132   = newFlexiTyVarTy liftedTypeKind      `thenM` \ any_ty ->
133     tcMonoExpr expr any_ty              `thenM_`
134     tcMetaTy expQTyConName
135         -- Result type is Expr (= Q Exp)
136
137 tc_bracket (TypBr typ) 
138   = tcHsSigType ExprSigCtxt typ         `thenM_`
139     tcMetaTy typeQTyConName
140         -- Result type is Type (= Q Typ)
141
142 tc_bracket (DecBr decls)
143   = do  {  tcTopSrcDecls emptyModDetails decls
144         -- Typecheck the declarations, dicarding the result
145         -- We'll get all that stuff later, when we splice it in
146
147         ; decl_ty <- tcMetaTy decTyConName
148         ; q_ty    <- tcMetaTy qTyConName
149         ; return (mkAppTy q_ty (mkListTy decl_ty))
150         -- Result type is Q [Dec]
151     }
152
153 tc_bracket (PatBr _)
154   = failWithTc (ptext SLIT("Tempate Haskell pattern brackets are not supported yet"))
155 \end{code}
156
157
158 %************************************************************************
159 %*                                                                      *
160 \subsection{Splicing an expression}
161 %*                                                                      *
162 %************************************************************************
163
164 \begin{code}
165 tcSpliceExpr (HsSplice name expr) res_ty
166   = setSrcSpan (getLoc expr)    $
167     getStage            `thenM` \ level ->
168     case spliceOK level of {
169         Nothing         -> failWithTc (illegalSplice level) ;
170         Just next_level -> 
171
172     case level of {
173         Comp                   -> do { e <- tcTopSplice expr res_ty
174                                      ; returnM (unLoc e) } ;
175         Brack _ ps_var lie_var ->  
176
177         -- A splice inside brackets
178         -- NB: ignore res_ty, apart from zapping it to a mono-type
179         -- e.g.   [| reverse $(h 4) |]
180         -- Here (h 4) :: Q Exp
181         -- but $(h 4) :: forall a.a     i.e. anything!
182
183     unBox res_ty                                `thenM_`
184     tcMetaTy expQTyConName                      `thenM` \ meta_exp_ty ->
185     setStage (Splice next_level) (
186         setLIEVar lie_var          $
187         tcMonoExpr expr meta_exp_ty
188     )                                           `thenM` \ expr' ->
189
190         -- Write the pending splice into the bucket
191     readMutVar ps_var                           `thenM` \ ps ->
192     writeMutVar ps_var ((name,expr') : ps)      `thenM_`
193
194     returnM (panic "tcSpliceExpr")      -- The returned expression is ignored
195     }} 
196
197 -- tcTopSplice used to have this:
198 -- Note that we do not decrement the level (to -1) before 
199 -- typechecking the expression.  For example:
200 --      f x = $( ...$(g 3) ... )
201 -- The recursive call to tcMonoExpr will simply expand the 
202 -- inner escape before dealing with the outer one
203
204 tcTopSplice :: LHsExpr Name -> BoxyRhoType -> TcM (LHsExpr Id)
205 tcTopSplice expr res_ty
206   = tcMetaTy expQTyConName              `thenM` \ meta_exp_ty ->
207
208         -- Typecheck the expression
209     tcTopSpliceExpr expr meta_exp_ty    `thenM` \ zonked_q_expr ->
210
211         -- Run the expression
212     traceTc (text "About to run" <+> ppr zonked_q_expr)         `thenM_`
213     runMetaE convertToHsExpr zonked_q_expr      `thenM` \ expr2 ->
214   
215     traceTc (text "Got result" <+> ppr expr2)   `thenM_`
216
217     showSplice "expression" 
218                zonked_q_expr (ppr expr2)        `thenM_`
219
220         -- Rename it, but bale out if there are errors
221         -- otherwise the type checker just gives more spurious errors
222     checkNoErrs (rnLExpr expr2)                 `thenM` \ (exp3, fvs) ->
223
224     tcMonoExpr exp3 res_ty
225
226
227 tcTopSpliceExpr :: LHsExpr Name -> TcType -> TcM (LHsExpr Id)
228 -- Type check an expression that is the body of a top-level splice
229 --   (the caller will compile and run it)
230 tcTopSpliceExpr expr meta_ty
231   = checkNoErrs $       -- checkNoErrs: must not try to run the thing
232                         --              if the type checker fails!
233
234     setStage topSpliceStage $ do
235
236         
237     do  { recordThUse   -- Record that TH is used (for pkg depdendency)
238
239         -- Typecheck the expression
240         ; (expr', lie) <- getLIE (tcMonoExpr expr meta_ty)
241         
242         -- Solve the constraints
243         ; const_binds <- tcSimplifyTop lie
244         
245         -- And zonk it
246         ; zonkTopLExpr (mkHsDictLet const_binds expr') }
247 \end{code}
248
249
250 %************************************************************************
251 %*                                                                      *
252                 Splicing a type
253 %*                                                                      *
254 %************************************************************************
255
256 Very like splicing an expression, but we don't yet share code.
257
258 \begin{code}
259 kcSpliceType (HsSplice name hs_expr)
260   = setSrcSpan (getLoc hs_expr) $ do    
261         { level <- getStage
262         ; case spliceOK level of {
263                 Nothing         -> failWithTc (illegalSplice level) ;
264                 Just next_level -> do 
265
266         { case level of {
267                 Comp                   -> do { (t,k) <- kcTopSpliceType hs_expr 
268                                              ; return (unLoc t, k) } ;
269                 Brack _ ps_var lie_var -> do
270
271         {       -- A splice inside brackets
272         ; meta_ty <- tcMetaTy typeQTyConName
273         ; expr' <- setStage (Splice next_level) $
274                    setLIEVar lie_var            $
275                    tcMonoExpr hs_expr meta_ty
276
277                 -- Write the pending splice into the bucket
278         ; ps <- readMutVar ps_var
279         ; writeMutVar ps_var ((name,expr') : ps)
280
281         -- e.g.   [| Int -> $(h 4) |]
282         -- Here (h 4) :: Q Type
283         -- but $(h 4) :: forall a.a     i.e. any kind
284         ; kind <- newKindVar
285         ; returnM (panic "kcSpliceType", kind)  -- The returned type is ignored
286     }}}}}
287
288 kcTopSpliceType :: LHsExpr Name -> TcM (LHsType Name, TcKind)
289 kcTopSpliceType expr
290   = do  { meta_ty <- tcMetaTy typeQTyConName
291
292         -- Typecheck the expression
293         ; zonked_q_expr <- tcTopSpliceExpr expr meta_ty
294
295         -- Run the expression
296         ; traceTc (text "About to run" <+> ppr zonked_q_expr)
297         ; hs_ty2 <- runMetaT convertToHsType zonked_q_expr
298   
299         ; traceTc (text "Got result" <+> ppr hs_ty2)
300
301         ; showSplice "type" zonked_q_expr (ppr hs_ty2)
302
303         -- Rename it, but bale out if there are errors
304         -- otherwise the type checker just gives more spurious errors
305         ; let doc = ptext SLIT("In the spliced type") <+> ppr hs_ty2
306         ; hs_ty3 <- checkNoErrs (rnLHsType doc hs_ty2)
307
308         ; kcHsType hs_ty3 }
309 \end{code}
310
311 %************************************************************************
312 %*                                                                      *
313 \subsection{Splicing an expression}
314 %*                                                                      *
315 %************************************************************************
316
317 \begin{code}
318 -- Always at top level
319 -- Type sig at top of file:
320 --      tcSpliceDecls :: LHsExpr Name -> TcM [LHsDecl RdrName]
321 tcSpliceDecls expr
322   = do  { meta_dec_ty <- tcMetaTy decTyConName
323         ; meta_q_ty <- tcMetaTy qTyConName
324         ; let list_q = mkAppTy meta_q_ty (mkListTy meta_dec_ty)
325         ; zonked_q_expr <- tcTopSpliceExpr expr list_q
326
327                 -- Run the expression
328         ; traceTc (text "About to run" <+> ppr zonked_q_expr)
329         ; decls <- runMetaD convertToHsDecls zonked_q_expr
330
331         ; traceTc (text "Got result" <+> vcat (map ppr decls))
332         ; showSplice "declarations"
333                      zonked_q_expr 
334                      (ppr (getLoc expr) $$ (vcat (map ppr decls)))
335         ; returnM decls }
336
337   where handleErrors :: [Either a Message] -> TcM [a]
338         handleErrors [] = return []
339         handleErrors (Left x:xs) = liftM (x:) (handleErrors xs)
340         handleErrors (Right m:xs) = do addErrTc m
341                                        handleErrors xs
342 \end{code}
343
344
345 %************************************************************************
346 %*                                                                      *
347 \subsection{Running an expression}
348 %*                                                                      *
349 %************************************************************************
350
351 \begin{code}
352 runMetaE :: (SrcSpan -> TH.Exp -> Either Message (LHsExpr RdrName))
353          -> LHsExpr Id          -- Of type (Q Exp)
354          -> TcM (LHsExpr RdrName)
355 runMetaE  = runMeta
356
357 runMetaT :: (SrcSpan -> TH.Type -> Either Message (LHsType RdrName))
358          -> LHsExpr Id          -- Of type (Q Type)
359          -> TcM (LHsType RdrName)       
360 runMetaT = runMeta
361
362 runMetaD :: (SrcSpan -> [TH.Dec] -> Either Message [LHsDecl RdrName])
363          -> LHsExpr Id          -- Of type Q [Dec]
364          -> TcM [LHsDecl RdrName]
365 runMetaD = runMeta 
366
367 runMeta :: (SrcSpan -> th_syn -> Either Message hs_syn)
368         -> LHsExpr Id           -- Of type X
369         -> TcM hs_syn           -- Of type t
370 runMeta convert expr
371   = do  { hsc_env <- getTopEnv
372         ; tcg_env <- getGblEnv
373         ; this_mod <- getModule
374         ; let type_env = tcg_type_env tcg_env
375               rdr_env  = tcg_rdr_env tcg_env
376
377         -- Compile and link it; might fail if linking fails
378         ; either_hval <- tryM $ ioToTcRn $
379                          HscMain.compileExpr 
380                                       hsc_env this_mod 
381                                       rdr_env type_env expr
382         ; case either_hval of {
383             Left exn   -> failWithTc (mk_msg "compile and link" exn) ;
384             Right hval -> do
385
386         {       -- Coerce it to Q t, and run it
387                 -- Running might fail if it throws an exception of any kind (hence tryAllM)
388                 -- including, say, a pattern-match exception in the code we are running
389                 --
390                 -- We also do the TH -> HS syntax conversion inside the same
391                 -- exception-cacthing thing so that if there are any lurking 
392                 -- exceptions in the data structure returned by hval, we'll
393                 -- encounter them inside the try
394           either_tval <- tryAllM $ do
395                 { th_syn <- TH.runQ (unsafeCoerce# hval)
396                 ; case convert (getLoc expr) th_syn of
397                     Left err     -> do { addErrTc err; return Nothing }
398                     Right hs_syn -> return (Just hs_syn) }
399
400         ; case either_tval of
401               Right (Just v) -> return v
402               Right Nothing  -> failM   -- Error already in Tc monad
403               Left exn       -> failWithTc (mk_msg "run" exn)   -- Exception
404         }}}
405   where
406     mk_msg s exn = vcat [text "Exception when trying to" <+> text s <+> text "compile-time code:",
407                          nest 2 (text (Panic.showException exn)),
408                          nest 2 (text "Code:" <+> ppr expr)]
409 \end{code}
410
411 To call runQ in the Tc monad, we need to make TcM an instance of Quasi:
412
413 \begin{code}
414 instance TH.Quasi (IOEnv (Env TcGblEnv TcLclEnv)) where
415   qNewName s = do { u <- newUnique 
416                   ; let i = getKey u
417                   ; return (TH.mkNameU s i) }
418
419   qReport True msg  = addErr (text msg)
420   qReport False msg = addReport (text msg)
421
422   qCurrentModule = do { m <- getModule;
423                         return (moduleNameString (moduleName m)) }
424                 -- ToDo: is throwing away the package name ok here?
425
426   qReify v = reify v
427
428         -- For qRecover, discard error messages if 
429         -- the recovery action is chosen.  Otherwise
430         -- we'll only fail higher up.  c.f. tryTcLIE_
431   qRecover recover main = do { (msgs, mb_res) <- tryTcErrs main
432                              ; case mb_res of
433                                  Just val -> do { addMessages msgs      -- There might be warnings
434                                                 ; return val }
435                                  Nothing  -> recover                    -- Discard all msgs
436                           }
437
438   qRunIO io = ioToTcRn io
439 \end{code}
440
441
442 %************************************************************************
443 %*                                                                      *
444 \subsection{Errors and contexts}
445 %*                                                                      *
446 %************************************************************************
447
448 \begin{code}
449 showSplice :: String -> LHsExpr Id -> SDoc -> TcM ()
450 showSplice what before after
451   = getSrcSpanM         `thenM` \ loc ->
452     traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what, 
453                        nest 2 (sep [nest 2 (ppr before),
454                                     text "======>",
455                                     nest 2 after])])
456
457 illegalBracket level
458   = ptext SLIT("Illegal bracket at level") <+> ppr level
459
460 illegalSplice level
461   = ptext SLIT("Illegal splice at level") <+> ppr level
462
463 #endif  /* GHCI */
464 \end{code}
465
466
467 %************************************************************************
468 %*                                                                      *
469                         Reification
470 %*                                                                      *
471 %************************************************************************
472
473
474 \begin{code}
475 reify :: TH.Name -> TcM TH.Info
476 reify th_name
477   = do  { name <- lookupThName th_name
478         ; thing <- tcLookupTh name
479                 -- ToDo: this tcLookup could fail, which would give a
480                 --       rather unhelpful error message
481         ; traceIf (text "reify" <+> text (show th_name) <+> brackets (ppr_ns th_name) <+> ppr name)
482         ; reifyThing thing
483     }
484   where
485     ppr_ns (TH.Name _ (TH.NameG TH.DataName _pkg _mod)) = text "data"
486     ppr_ns (TH.Name _ (TH.NameG TH.TcClsName _pkg _mod)) = text "tc"
487     ppr_ns (TH.Name _ (TH.NameG TH.VarName _pkg _mod)) = text "var"
488
489 lookupThName :: TH.Name -> TcM Name
490 lookupThName th_name@(TH.Name occ flavour)
491   =  do { let rdr_name = thRdrName guessed_ns occ_str flavour
492
493         -- Repeat much of lookupOccRn, becase we want
494         -- to report errors in a TH-relevant way
495         ; rdr_env <- getLocalRdrEnv
496         ; case lookupLocalRdrEnv rdr_env rdr_name of
497             Just name -> return name
498             Nothing | not (isSrcRdrName rdr_name)       -- Exact, Orig
499                     -> lookupImportedName rdr_name
500                     | otherwise                         -- Unqual, Qual
501                     -> do { 
502                                   mb_name <- lookupSrcOcc_maybe rdr_name
503                           ; case mb_name of
504                               Just name -> return name
505                               Nothing   -> failWithTc (notInScope th_name) }
506         }
507   where
508         -- guessed_ns is the name space guessed from looking at the TH name
509     guessed_ns | isLexCon (mkFastString occ_str) = OccName.dataName
510                | otherwise                       = OccName.varName
511     occ_str = TH.occString occ
512
513 tcLookupTh :: Name -> TcM TcTyThing
514 -- This is a specialised version of TcEnv.tcLookup; specialised mainly in that
515 -- it gives a reify-related error message on failure, whereas in the normal
516 -- tcLookup, failure is a bug.
517 tcLookupTh name
518   = do  { (gbl_env, lcl_env) <- getEnvs
519         ; case lookupNameEnv (tcl_env lcl_env) name of {
520                 Just thing -> returnM thing;
521                 Nothing    -> do
522         { if nameIsLocalOrFrom (tcg_mod gbl_env) name
523           then  -- It's defined in this module
524               case lookupNameEnv (tcg_type_env gbl_env) name of
525                 Just thing -> return (AGlobal thing)
526                 Nothing    -> failWithTc (notInEnv name)
527          
528           else do               -- It's imported
529         { (eps,hpt) <- getEpsAndHpt
530         ; dflags <- getDOpts
531         ; case lookupType dflags hpt (eps_PTE eps) name of 
532             Just thing -> return (AGlobal thing)
533             Nothing    -> do { thing <- tcImportDecl name
534                              ; return (AGlobal thing) }
535                 -- Imported names should always be findable; 
536                 -- if not, we fail hard in tcImportDecl
537     }}}}
538
539 notInScope :: TH.Name -> SDoc
540 notInScope th_name = quotes (text (TH.pprint th_name)) <+> 
541                      ptext SLIT("is not in scope at a reify")
542         -- Ugh! Rather an indirect way to display the name
543
544 notInEnv :: Name -> SDoc
545 notInEnv name = quotes (ppr name) <+> 
546                      ptext SLIT("is not in the type environment at a reify")
547
548 ------------------------------
549 reifyThing :: TcTyThing -> TcM TH.Info
550 -- The only reason this is monadic is for error reporting,
551 -- which in turn is mainly for the case when TH can't express
552 -- some random GHC extension
553
554 reifyThing (AGlobal (AnId id))
555   = do  { ty <- reifyType (idType id)
556         ; fix <- reifyFixity (idName id)
557         ; let v = reifyName id
558         ; case globalIdDetails id of
559             ClassOpId cls    -> return (TH.ClassOpI v ty (reifyName cls) fix)
560             other            -> return (TH.VarI     v ty Nothing fix)
561     }
562
563 reifyThing (AGlobal (ATyCon tc))  = reifyTyCon tc
564 reifyThing (AGlobal (AClass cls)) = reifyClass cls
565 reifyThing (AGlobal (ADataCon dc))
566   = do  { let name = dataConName dc
567         ; ty <- reifyType (idType (dataConWrapId dc))
568         ; fix <- reifyFixity name
569         ; return (TH.DataConI (reifyName name) ty (reifyName (dataConTyCon dc)) fix) }
570
571 reifyThing (ATcId id _ _) 
572   = do  { ty1 <- zonkTcType (idType id) -- Make use of all the info we have, even
573                                         -- though it may be incomplete
574         ; ty2 <- reifyType ty1
575         ; fix <- reifyFixity (idName id)
576         ; return (TH.VarI (reifyName id) ty2 Nothing fix) }
577
578 reifyThing (ATyVar tv ty) 
579   = do  { ty1 <- zonkTcType ty
580         ; ty2 <- reifyType ty1
581         ; return (TH.TyVarI (reifyName tv) ty2) }
582
583 ------------------------------
584 reifyTyCon :: TyCon -> TcM TH.Info
585 reifyTyCon tc
586   | isFunTyCon tc  = return (TH.PrimTyConI (reifyName tc) 2               False)
587   | isPrimTyCon tc = return (TH.PrimTyConI (reifyName tc) (tyConArity tc) (isUnLiftedTyCon tc))
588   | isSynTyCon tc
589   = do  { let (tvs, rhs) = synTyConDefn tc
590         ; rhs' <- reifyType rhs
591         ; return (TH.TyConI $ TH.TySynD (reifyName tc) (reifyTyVars tvs) rhs') }
592
593 reifyTyCon tc
594   = do  { cxt <- reifyCxt (tyConStupidTheta tc)
595         ; cons <- mapM reifyDataCon (tyConDataCons tc)
596         ; let name = reifyName tc
597               tvs  = reifyTyVars (tyConTyVars tc)
598               deriv = []        -- Don't know about deriving
599               decl | isNewTyCon tc = TH.NewtypeD cxt name tvs (head cons) deriv
600                    | otherwise     = TH.DataD    cxt name tvs cons        deriv
601         ; return (TH.TyConI decl) }
602
603 reifyDataCon :: DataCon -> TcM TH.Con
604 reifyDataCon dc
605   | isVanillaDataCon dc
606   = do  { arg_tys <- reifyTypes (dataConOrigArgTys dc)
607         ; let stricts = map reifyStrict (dataConStrictMarks dc)
608               fields  = dataConFieldLabels dc
609               name    = reifyName dc
610               [a1,a2] = arg_tys
611               [s1,s2] = stricts
612         ; ASSERT( length arg_tys == length stricts )
613           if not (null fields) then
614              return (TH.RecC name (zip3 (map reifyName fields) stricts arg_tys))
615           else
616           if dataConIsInfix dc then
617              ASSERT( length arg_tys == 2 )
618              return (TH.InfixC (s1,a1) name (s2,a2))
619           else
620              return (TH.NormalC name (stricts `zip` arg_tys)) }
621   | otherwise
622   = failWithTc (ptext SLIT("Can't reify a non-Haskell-98 data constructor:") 
623                 <+> quotes (ppr dc))
624
625 ------------------------------
626 reifyClass :: Class -> TcM TH.Info
627 reifyClass cls 
628   = do  { cxt <- reifyCxt theta
629         ; ops <- mapM reify_op op_stuff
630         ; return (TH.ClassI $ TH.ClassD cxt (reifyName cls) (reifyTyVars tvs) fds' ops) }
631   where
632     (tvs, fds, theta, _, op_stuff) = classExtraBigSig cls
633     fds' = map reifyFunDep fds
634     reify_op (op, _) = do { ty <- reifyType (idType op)
635                           ; return (TH.SigD (reifyName op) ty) }
636
637 ------------------------------
638 reifyType :: TypeRep.Type -> TcM TH.Type
639 reifyType (TyVarTy tv)      = return (TH.VarT (reifyName tv))
640 reifyType (TyConApp tc tys) = reify_tc_app (reifyName tc) tys
641 reifyType (NoteTy _ ty)     = reifyType ty
642 reifyType (AppTy t1 t2)     = do { [r1,r2] <- reifyTypes [t1,t2] ; return (r1 `TH.AppT` r2) }
643 reifyType (FunTy t1 t2)     = do { [r1,r2] <- reifyTypes [t1,t2] ; return (TH.ArrowT `TH.AppT` r1 `TH.AppT` r2) }
644 reifyType ty@(ForAllTy _ _) = do { cxt' <- reifyCxt cxt; 
645                                  ; tau' <- reifyType tau 
646                                  ; return (TH.ForallT (reifyTyVars tvs) cxt' tau') }
647                             where
648                                 (tvs, cxt, tau) = tcSplitSigmaTy ty
649 reifyTypes = mapM reifyType
650 reifyCxt   = mapM reifyPred
651
652 reifyFunDep :: ([TyVar], [TyVar]) -> TH.FunDep
653 reifyFunDep (xs, ys) = TH.FunDep (map reifyName xs) (map reifyName ys)
654
655 reifyTyVars :: [TyVar] -> [TH.Name]
656 reifyTyVars = map reifyName
657
658 reify_tc_app :: TH.Name -> [TypeRep.Type] -> TcM TH.Type
659 reify_tc_app tc tys = do { tys' <- reifyTypes tys 
660                          ; return (foldl TH.AppT (TH.ConT tc) tys') }
661
662 reifyPred :: TypeRep.PredType -> TcM TH.Type
663 reifyPred (ClassP cls tys) = reify_tc_app (reifyName cls) tys
664 reifyPred p@(IParam _ _)   = noTH SLIT("implicit parameters") (ppr p)
665
666
667 ------------------------------
668 reifyName :: NamedThing n => n -> TH.Name
669 reifyName thing
670   | isExternalName name = mk_varg pkg_str mod_str occ_str
671   | otherwise           = TH.mkNameU occ_str (getKey (getUnique name))
672         -- Many of the things we reify have local bindings, and 
673         -- NameL's aren't supposed to appear in binding positions, so
674         -- we use NameU.  When/if we start to reify nested things, that
675         -- have free variables, we may need to generate NameL's for them.
676   where
677     name    = getName thing
678     mod     = nameModule name
679     pkg_str = packageIdString (modulePackageId mod)
680     mod_str = moduleNameString (moduleName mod)
681     occ_str = occNameString occ
682     occ     = nameOccName name
683     mk_varg | OccName.isDataOcc occ = TH.mkNameG_d
684             | OccName.isVarOcc  occ = TH.mkNameG_v
685             | OccName.isTcOcc   occ = TH.mkNameG_tc
686             | otherwise             = pprPanic "reifyName" (ppr name)
687
688 ------------------------------
689 reifyFixity :: Name -> TcM TH.Fixity
690 reifyFixity name
691   = do  { fix <- lookupFixityRn name
692         ; return (conv_fix fix) }
693     where
694       conv_fix (BasicTypes.Fixity i d) = TH.Fixity i (conv_dir d)
695       conv_dir BasicTypes.InfixR = TH.InfixR
696       conv_dir BasicTypes.InfixL = TH.InfixL
697       conv_dir BasicTypes.InfixN = TH.InfixN
698
699 reifyStrict :: BasicTypes.StrictnessMark -> TH.Strict
700 reifyStrict MarkedStrict    = TH.IsStrict
701 reifyStrict MarkedUnboxed   = TH.IsStrict
702 reifyStrict NotMarkedStrict = TH.NotStrict
703
704 ------------------------------
705 noTH :: LitString -> SDoc -> TcM a
706 noTH s d = failWithTc (hsep [ptext SLIT("Can't represent") <+> ptext s <+> 
707                                 ptext SLIT("in Template Haskell:"),
708                              nest 2 d])
709 \end{code}