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