[project @ 2004-11-18 00:56:18 by igloo]
[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 )
23 import RnExpr           ( rnLExpr )
24 import RnEnv            ( lookupFixityRn, lookupSrcOcc_maybe )
25 import RdrName          ( RdrName, mkRdrUnqual, lookupLocalRdrEnv )
26 import RnTypes          ( rnLHsType )
27 import TcExpr           ( tcCheckRho, tcMonoExpr )
28 import TcHsSyn          ( mkHsLet, 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, zonkTcTyVar )
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                           mkInternalName, nameIsLocalOrFrom )
39 import NameEnv          ( lookupNameEnv )
40 import HscTypes         ( lookupType, ExternalPackageState(..) )
41 import OccName
42 import Var              ( Id, TyVar, idType )
43 import Module           ( moduleUserString, mkModuleName )
44 import TcRnMonad
45 import IfaceEnv         ( lookupOrig )
46 import Class            ( Class, classExtraBigSig )
47 import TyCon            ( TyCon, AlgTyConRhs(..), tyConTyVars, getSynTyConDefn, 
48                           isSynTyCon, isNewTyCon, tyConDataCons, algTyConRhs )
49 import DataCon          ( DataCon, dataConTyCon, dataConOrigArgTys, dataConStrictMarks, 
50                           dataConName, dataConFieldLabels, dataConWrapId, dataConIsInfix, 
51                           isVanillaDataCon )
52 import Id               ( idName, globalIdDetails )
53 import IdInfo           ( GlobalIdDetails(..) )
54 import TysWiredIn       ( mkListTy )
55 import DsMeta           ( expQTyConName, typeQTyConName, decTyConName, qTyConName, nameTyConName )
56 import ErrUtils         ( Message )
57 import SrcLoc           ( noLoc, unLoc, getLoc, noSrcLoc )
58 import Outputable
59 import Unique           ( Unique, Uniquable(..), getKey, mkUniqueGrimily )
60
61 import BasicTypes       ( StrictnessMark(..), Fixity(..), FixityDirection(..) )
62 import Panic            ( showException )
63 import FastString       ( LitString )
64
65 import GHC.Base         ( unsafeCoerce#, Int#, Int(..) )        -- Should have a better home in the module hierarchy
66 import Monad            ( liftM )
67 import Maybes           ( orElse )
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
129         -- 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   = tcTopSrcDecls [{- no boot-names -}] decls           `thenM_`
144         -- Typecheck the declarations, dicarding the result
145         -- We'll get all that stuff later, when we splice it in
146
147     tcMetaTy decTyConName       `thenM` \ decl_ty ->
148     tcMetaTy qTyConName         `thenM` \ q_ty ->
149     returnM (mkAppTy q_ty (mkListTy decl_ty))
150         -- Result type is Q [Dec]
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 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 (mkHsLet 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 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 tcSpliceDecls expr
326   = do  { meta_dec_ty <- tcMetaTy decTyConName
327         ; meta_q_ty <- tcMetaTy qTyConName
328         ; let list_q = mkAppTy meta_q_ty (mkListTy meta_dec_ty)
329         ; zonked_q_expr <- tcTopSpliceExpr expr list_q
330
331                 -- Run the expression
332         ; traceTc (text "About to run" <+> ppr zonked_q_expr)
333         ; simple_expr <- runMetaD zonked_q_expr
334
335             -- simple_expr :: [TH.Dec]
336             -- decls :: [RdrNameHsDecl]
337         ; decls <- handleErrors (convertToHsDecls simple_expr)
338         ; traceTc (text "Got result" <+> vcat (map ppr decls))
339         ; showSplice "declarations"
340                      zonked_q_expr (vcat (map ppr decls))
341         ; returnM decls }
342
343   where handleErrors :: [Either a Message] -> TcM [a]
344         handleErrors [] = return []
345         handleErrors (Left x:xs) = liftM (x:) (handleErrors xs)
346         handleErrors (Right m:xs) = do addErrTc m
347                                        handleErrors xs
348 \end{code}
349
350
351 %************************************************************************
352 %*                                                                      *
353 \subsection{Running an expression}
354 %*                                                                      *
355 %************************************************************************
356
357 \begin{code}
358 runMetaE :: LHsExpr Id  -- Of type (Q Exp)
359          -> TcM TH.Exp  -- Of type Exp
360 runMetaE e = runMeta e
361
362 runMetaT :: LHsExpr Id          -- Of type (Q Type)
363          -> TcM TH.Type         -- Of type Type
364 runMetaT e = runMeta e
365
366 runMetaD :: LHsExpr Id          -- Of type Q [Dec]
367          -> TcM [TH.Dec]        -- Of type [Dec]
368 runMetaD e = runMeta e
369
370 runMeta :: LHsExpr Id           -- Of type X
371         -> TcM t                -- Of type t
372 runMeta expr
373   = do  { hsc_env <- getTopEnv
374         ; tcg_env <- getGblEnv
375         ; this_mod <- getModule
376         ; let type_env = tcg_type_env tcg_env
377               rdr_env  = tcg_rdr_env tcg_env
378         -- Wrap the compile-and-run in an exception-catcher
379         -- Compiling might fail if linking fails
380         -- Running might fail if it throws an exception
381         ; either_tval <- tryM $ do
382                 {       -- Compile it
383                   hval <- ioToTcRn (HscMain.compileExpr 
384                                       hsc_env this_mod 
385                                       rdr_env type_env expr)
386                         -- Coerce it to Q t, and run it
387                 ; TH.runQ (unsafeCoerce# hval) }
388
389         ; case either_tval of
390               Left exn -> failWithTc (vcat [text "Exception when trying to run compile-time code:", 
391                                             nest 4 (vcat [text "Code:" <+> ppr expr,
392                                                       text ("Exn: " ++ Panic.showException exn)])])
393               Right v  -> returnM v }
394 \end{code}
395
396 To call runQ in the Tc monad, we need to make TcM an instance of Quasi:
397
398 \begin{code}
399 instance TH.Quasi (IOEnv (Env TcGblEnv TcLclEnv)) where
400   qNewName s = do  { u <- newUnique 
401                   ; let i = getKey u
402                   ; return (TH.mkNameU s i) }
403
404   qReport True msg  = addErr (text msg)
405   qReport False msg = addReport (text msg)
406
407   qCurrentModule = do { m <- getModule; return (moduleUserString m) }
408   qReify v = reify v
409   qRecover = recoverM
410
411   qRunIO io = ioToTcRn io
412 \end{code}
413
414
415 %************************************************************************
416 %*                                                                      *
417 \subsection{Errors and contexts}
418 %*                                                                      *
419 %************************************************************************
420
421 \begin{code}
422 showSplice :: String -> LHsExpr Id -> SDoc -> TcM ()
423 showSplice what before after
424   = getSrcSpanM         `thenM` \ loc ->
425     traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what, 
426                        nest 2 (sep [nest 2 (ppr before),
427                                     text "======>",
428                                     nest 2 after])])
429
430 illegalBracket level
431   = ptext SLIT("Illegal bracket at level") <+> ppr level
432
433 illegalSplice level
434   = ptext SLIT("Illegal splice at level") <+> ppr level
435
436 #endif  /* GHCI */
437 \end{code}
438
439
440 %************************************************************************
441 %*                                                                      *
442                         Reification
443 %*                                                                      *
444 %************************************************************************
445
446
447 \begin{code}
448 reify :: TH.Name -> TcM TH.Info
449 reify th_name
450   = do  { name <- lookupThName th_name
451         ; thing <- tcLookupTh name
452                 -- ToDo: this tcLookup could fail, which would give a
453                 --       rather unhelpful error message
454         ; reifyThing thing
455     }
456
457 lookupThName :: TH.Name -> TcM Name
458 lookupThName (TH.Name occ (TH.NameG th_ns mod))
459   = lookupOrig (mkModuleName (TH.modString mod))
460                (OccName.mkOccName ghc_ns (TH.occString occ))
461   where
462     ghc_ns = case th_ns of
463                 TH.DataName  -> dataName
464                 TH.TcClsName -> tcClsName
465                 TH.VarName   -> varName
466
467 lookupThName th_name@(TH.Name occ TH.NameS) 
468   =  do { let rdr_name = mkRdrUnqual (OccName.mkOccFS ns occ_fs)
469         ; rdr_env <- getLocalRdrEnv
470         ; case lookupLocalRdrEnv rdr_env rdr_name of
471                 Just name -> return name
472                 Nothing   -> do
473         { mb_name <- lookupSrcOcc_maybe rdr_name
474         ; case mb_name of
475             Just name -> return name ;
476             Nothing   -> failWithTc (notInScope th_name)
477         }}
478   where
479     ns | isLexCon occ_fs = OccName.dataName
480        | otherwise       = OccName.varName
481     occ_fs = mkFastString (TH.occString occ)
482
483 lookupThName (TH.Name occ (TH.NameU uniq)) 
484   = return (mkInternalName (mk_uniq uniq) (OccName.mkOccFS bogus_ns occ_fs) noSrcLoc)
485   where
486     occ_fs = mkFastString (TH.occString occ)
487     bogus_ns = OccName.varName  -- Not yet recorded in the TH name
488                                 -- but only the unique matters
489
490 tcLookupTh :: Name -> TcM TcTyThing
491 -- This is a specialised version of TcEnv.tcLookup; specialised mainly in that
492 -- it gives a reify-related error message on failure, whereas in the normal
493 -- tcLookup, failure is a bug.
494 tcLookupTh name
495   = do  { (gbl_env, lcl_env) <- getEnvs
496         ; case lookupNameEnv (tcl_env lcl_env) name of
497                 Just thing -> returnM thing
498                 Nothing    -> do
499         { if nameIsLocalOrFrom (tcg_mod gbl_env) name
500           then  -- It's defined in this module
501               case lookupNameEnv (tcg_type_env gbl_env) name of
502                 Just thing -> return (AGlobal thing)
503                 Nothing    -> failWithTc (notInEnv name)
504          
505           else do               -- It's imported
506         { (eps,hpt) <- getEpsAndHpt
507         ; case lookupType hpt (eps_PTE eps) name of 
508             Just thing -> return (AGlobal thing)
509             Nothing    -> do { traceIf (text "tcLookupGlobal" <+> ppr name)
510                              ; thing <- initIfaceTcRn (tcImportDecl name)
511                              ; return (AGlobal thing) }
512                 -- Imported names should always be findable; 
513                 -- if not, we fail hard in tcImportDecl
514     }}}
515
516 mk_uniq :: Int# -> Unique
517 mk_uniq u = mkUniqueGrimily (I# u)
518
519 notInScope :: TH.Name -> SDoc
520 notInScope th_name = quotes (text (TH.pprint th_name)) <+> 
521                      ptext SLIT("is not in scope at a reify")
522         -- Ugh! Rather an indirect way to display the name
523
524 notInEnv :: Name -> SDoc
525 notInEnv name = quotes (ppr name) <+> 
526                      ptext SLIT("is not in the type environment at a reify")
527
528 ------------------------------
529 reifyThing :: TcTyThing -> TcM TH.Info
530 -- The only reason this is monadic is for error reporting,
531 -- which in turn is mainly for the case when TH can't express
532 -- some random GHC extension
533
534 reifyThing (AGlobal (AnId id))
535   = do  { ty <- reifyType (idType id)
536         ; fix <- reifyFixity (idName id)
537         ; let v = reifyName id
538         ; case globalIdDetails id of
539             ClassOpId cls    -> return (TH.ClassOpI v ty (reifyName cls) fix)
540             other            -> return (TH.VarI     v ty Nothing fix)
541     }
542
543 reifyThing (AGlobal (ATyCon tc))   = do { dec <- reifyTyCon tc;  return (TH.TyConI dec) }
544 reifyThing (AGlobal (AClass cls))  = do { dec <- reifyClass cls; return (TH.ClassI dec) }
545 reifyThing (AGlobal (ADataCon dc))
546   = do  { let name = dataConName dc
547         ; ty <- reifyType (idType (dataConWrapId dc))
548         ; fix <- reifyFixity name
549         ; return (TH.DataConI (reifyName name) ty (reifyName (dataConTyCon dc)) fix) }
550
551 reifyThing (ATcId id _ _) 
552   = do  { ty1 <- zonkTcType (idType id) -- Make use of all the info we have, even
553                                         -- though it may be incomplete
554         ; ty2 <- reifyType ty1
555         ; fix <- reifyFixity (idName id)
556         ; return (TH.VarI (reifyName id) ty2 Nothing fix) }
557
558 reifyThing (ATyVar tv) 
559   = do  { ty1 <- zonkTcTyVar tv
560         ; ty2 <- reifyType ty1
561         ; return (TH.TyVarI (reifyName tv) ty2) }
562
563 ------------------------------
564 reifyTyCon :: TyCon -> TcM TH.Dec
565 reifyTyCon tc
566   | isSynTyCon tc
567   = do  { let (tvs, rhs) = getSynTyConDefn tc
568         ; rhs' <- reifyType rhs
569         ; return (TH.TySynD (reifyName tc) (reifyTyVars tvs) rhs') }
570
571 reifyTyCon tc
572   = case algTyConRhs tc of
573       NewTyCon data_con _ _ 
574         -> do   { con <- reifyDataCon data_con
575                 ; return (TH.NewtypeD [] (reifyName tc) (reifyTyVars (tyConTyVars tc))
576                                       con [{- Don't know about deriving -}]) }
577
578       DataTyCon mb_cxt cons _
579         -> do   { cxt <- reifyCxt (mb_cxt `orElse` [])
580                 ; cons <- mapM reifyDataCon (tyConDataCons tc)
581                 ; return (TH.DataD cxt (reifyName tc) (reifyTyVars (tyConTyVars tc))
582                                       cons [{- Don't know about deriving -}]) }
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 (s1,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.Dec
608 reifyClass cls 
609   = do  { cxt <- reifyCxt theta
610         ; ops <- mapM reify_op op_stuff
611         ; return (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   where
654     name    = getName thing
655     mod     = moduleUserString (nameModule name)
656     occ_str = occNameUserString occ
657     occ     = nameOccName name
658     mk_varg | OccName.isDataOcc occ = TH.mkNameG_d
659             | OccName.isVarOcc  occ = TH.mkNameG_v
660             | OccName.isTcOcc   occ = TH.mkNameG_tc
661             | otherwise             = pprPanic "reifyName" (ppr name)
662
663 ------------------------------
664 reifyFixity :: Name -> TcM TH.Fixity
665 reifyFixity name
666   = do  { fix <- lookupFixityRn name
667         ; return (conv_fix fix) }
668     where
669       conv_fix (BasicTypes.Fixity i d) = TH.Fixity i (conv_dir d)
670       conv_dir BasicTypes.InfixR = TH.InfixR
671       conv_dir BasicTypes.InfixL = TH.InfixL
672       conv_dir BasicTypes.InfixN = TH.InfixN
673
674 reifyStrict :: BasicTypes.StrictnessMark -> TH.Strict
675 reifyStrict MarkedStrict    = TH.IsStrict
676 reifyStrict MarkedUnboxed   = TH.IsStrict
677 reifyStrict NotMarkedStrict = TH.NotStrict
678
679 ------------------------------
680 noTH :: LitString -> SDoc -> TcM a
681 noTH s d = failWithTc (hsep [ptext SLIT("Can't represent") <+> ptext s <+> 
682                                 ptext SLIT("in Template Haskell:"),
683                              nest 2 d])
684 \end{code}