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