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