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