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