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