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