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