TcSplice.lhs 23.7 KB
Newer Older
1
%
2
3
4
5
6
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
%
\section[TcSplice]{Template Haskell splices}

\begin{code}
7
module TcSplice( tcSpliceExpr, tcSpliceDecls, tcBracket ) where
8
9
10
11

#include "HsVersions.h"

import HscMain		( compileExpr )
12
import TcRnDriver	( tcTopSrcDecls )
13
14
15
	-- These imports are the reason that TcSplice 
	-- is very high up the module hierarchy

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
21
import HsSyn		( HsBracket(..), HsExpr(..), HsSplice(..), LHsExpr, LHsDecl, 
		   	  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		( tcMonoExpr )
28
import TcHsSyn		( mkHsDictLet, zonkTopLExpr )
29
import TcSimplify	( tcSimplifyTop, tcSimplifyBracket )
30
31
import TcUnify		( boxyUnify, unBox )
import TcType		( TcType, TcKind, BoxyRhoType, liftedTypeKind, mkAppTy, tcSplitSigmaTy )
32
import TcEnv		( spliceOK, tcMetaTy, bracketOK )
33
import TcMType		( newFlexiTyVarTy, 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 )
Simon Marlow's avatar
Simon Marlow committed
44
import Module		( moduleName, moduleNameString, modulePackageId )
45
import TcRnMonad
46
import IfaceEnv		( lookupOrig )
47
import Class		( Class, classExtraBigSig )
48
import TyCon		( TyCon, tyConTyVars, synTyConDefn, 
49
			  isSynTyCon, isNewTyCon, tyConDataCons, isPrimTyCon, isFunTyCon,
50
			  tyConArity, tyConStupidTheta, isUnLiftedTyCon )
51
import DataCon		( DataCon, dataConTyCon, dataConOrigArgTys, dataConStrictMarks, 
52
53
			  dataConName, dataConFieldLabels, dataConWrapId, dataConIsInfix, 
			  isVanillaDataCon )
54
55
import Id		( idName, globalIdDetails )
import IdInfo		( GlobalIdDetails(..) )
56
import TysWiredIn	( mkListTy )
57
58
import DsMeta		( expQTyConName, typeQTyConName, decTyConName, qTyConName, nameTyConName )
import ErrUtils		( Message )
59
import SrcLoc		( SrcSpan, noLoc, unLoc, getLoc )
60
import Outputable
61
import Unique		( Unique, Uniquable(..), getKey, mkUniqueGrimily )
Simon Marlow's avatar
Simon Marlow committed
62
import PackageConfig    ( packageIdString )
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
71
72

#ifdef GHCI
import FastString	( mkFastString )
#endif
73
74
75
76
77
78
79
80
81
82
\end{code}


%************************************************************************
%*									*
\subsection{Main interface + stubs for the non-GHCI case
%*									*
%************************************************************************

\begin{code}
83
tcSpliceDecls :: LHsExpr Name -> TcM [LHsDecl RdrName]
84
tcSpliceExpr  :: HsSplice Name -> BoxyRhoType -> TcM (HsExpr TcId)
85
kcSpliceType  :: HsSplice Name -> TcM (HsType Name, TcKind)
86
87
88
89
90
91
92
93
94

#ifndef GHCI
tcSpliceExpr n e ty = pprPanic "Cant do tcSpliceExpr without GHCi" (ppr e)
tcSpliceDecls e     = pprPanic "Cant do tcSpliceDecls without GHCi" (ppr e)
#else
\end{code}

%************************************************************************
%*									*
95
\subsection{Quoting an expression}
96
97
98
%*									*
%************************************************************************

99
\begin{code}
100
tcBracket :: HsBracket Name -> BoxyRhoType -> TcM (LHsExpr TcId)
101
tcBracket brack res_ty
102
103
104
105
106
107
108
109
  = getStage 				`thenM` \ level ->
    case bracketOK level of {
	Nothing         -> failWithTc (illegalBracket level) ;
	Just next_level ->

   	-- Typecheck expr to make sure it is valid,
	-- but throw away the results.  We'll type check
	-- it again when we actually use it.
110
    recordThUse				`thenM_`
111
112
113
114
115
116
117
118
    newMutVar []	 		`thenM` \ pending_splices ->
    getLIEVar				`thenM` \ lie_var ->

    setStage (Brack next_level pending_splices lie_var) (
	getLIE (tc_bracket brack)
    )					`thenM` \ (meta_ty, lie) ->
    tcSimplifyBracket lie 		`thenM_`  

119
	-- Make the expected type have the right shape
120
    boxyUnify meta_ty res_ty		`thenM_`
121
122
123

	-- Return the original expression, not the type-decorated one
    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
133
  = newFlexiTyVarTy liftedTypeKind	`thenM` \ any_ty ->
    tcMonoExpr expr any_ty		`thenM_`
134
    tcMetaTy expQTyConName
135
	-- Result type is Expr (= Q Exp)
136

137
138
tc_bracket (TypBr typ) 
  = tcHsSigType ExprSigCtxt typ		`thenM_`
139
    tcMetaTy typeQTyConName
140
141
	-- Result type is Type (= Q Typ)

142
tc_bracket (DecBr decls)
143
  = do	{  tcTopSrcDecls emptyModDetails decls
144
145
146
	-- Typecheck the declarations, dicarding the result
	-- We'll get all that stuff later, when we splice it in

147
148
149
	; decl_ty <- tcMetaTy decTyConName
	; q_ty    <- tcMetaTy qTyConName
	; return (mkAppTy q_ty (mkListTy decl_ty))
150
	-- Result type is Q [Dec]
151
    }
152
153
154

tc_bracket (PatBr _)
  = failWithTc (ptext SLIT("Tempate Haskell pattern brackets are not supported yet"))
155
156
\end{code}

157

158
159
160
161
162
163
%************************************************************************
%*									*
\subsection{Splicing an expression}
%*									*
%************************************************************************

164
\begin{code}
165
tcSpliceExpr (HsSplice name expr) res_ty
166
  = setSrcSpan (getLoc expr) 	$
167
    getStage		`thenM` \ level ->
168
169
170
171
172
    case spliceOK level of {
	Nothing 	-> failWithTc (illegalSplice level) ;
	Just next_level -> 

    case level of {
173
174
	Comp 		       -> do { e <- tcTopSplice expr res_ty
				     ; returnM (unLoc e) } ;
175
176
177
	Brack _ ps_var lie_var ->  

	-- A splice inside brackets
178
  	-- NB: ignore res_ty, apart from zapping it to a mono-type
179
180
181
182
	-- e.g.   [| reverse $(h 4) |]
	-- Here (h 4) :: Q Exp
	-- but $(h 4) :: forall a.a 	i.e. anything!

183
    unBox res_ty				`thenM_`
184
    tcMetaTy expQTyConName			`thenM` \ meta_exp_ty ->
185
186
    setStage (Splice next_level) (
	setLIEVar lie_var	   $
187
	tcMonoExpr expr meta_exp_ty
188
189
190
191
192
193
194
195
196
197
198
199
200
    )						`thenM` \ expr' ->

	-- Write the pending splice into the bucket
    readMutVar ps_var				`thenM` \ ps ->
    writeMutVar ps_var ((name,expr') : ps) 	`thenM_`

    returnM (panic "tcSpliceExpr")	-- The returned expression is ignored
    }} 

-- tcTopSplice used to have this:
-- Note that we do not decrement the level (to -1) before 
-- typechecking the expression.  For example:
--	f x = $( ...$(g 3) ... )
201
-- The recursive call to tcMonoExpr will simply expand the 
202
203
-- inner escape before dealing with the outer one

204
tcTopSplice :: LHsExpr Name -> BoxyRhoType -> TcM (LHsExpr Id)
205
tcTopSplice expr res_ty
206
  = tcMetaTy expQTyConName		`thenM` \ meta_exp_ty ->
207

208
209
	-- Typecheck the expression
    tcTopSpliceExpr expr meta_exp_ty	`thenM` \ zonked_q_expr ->
210
211
212

	-- Run the expression
    traceTc (text "About to run" <+> ppr zonked_q_expr) 	`thenM_`
213
    runMetaE convertToHsExpr zonked_q_expr	`thenM` \ expr2 ->
214
215
  
    traceTc (text "Got result" <+> ppr expr2) 	`thenM_`
216
217
218

    showSplice "expression" 
	       zonked_q_expr (ppr expr2)	`thenM_`
219
220
221

	-- Rename it, but bale out if there are errors
	-- otherwise the type checker just gives more spurious errors
222
    checkNoErrs (rnLExpr expr2)			`thenM` \ (exp3, fvs) ->
223

224
    tcMonoExpr exp3 res_ty
225
226


227
tcTopSpliceExpr :: LHsExpr Name -> TcType -> TcM (LHsExpr Id)
228
229
-- Type check an expression that is the body of a top-level splice
--   (the caller will compile and run it)
230
231
232
233
tcTopSpliceExpr expr meta_ty
  = checkNoErrs $	-- checkNoErrs: must not try to run the thing
			--	        if the type checker fails!

234
    setStage topSpliceStage $ do
235

236
237
	
    do	{ recordThUse	-- Record that TH is used (for pkg depdendency)
238

239
	-- Typecheck the expression
240
	; (expr', lie) <- getLIE (tcMonoExpr expr meta_ty)
241
	
242
	-- Solve the constraints
243
	; const_binds <- tcSimplifyTop lie
244
245
	
	-- And zonk it
246
	; zonkTopLExpr (mkHsDictLet const_binds expr') }
247
248
249
\end{code}


250
251
252
253
254
255
256
257
258
259
%************************************************************************
%*									*
		Splicing a type
%*									*
%************************************************************************

Very like splicing an expression, but we don't yet share code.

\begin{code}
kcSpliceType (HsSplice name hs_expr)
260
  = setSrcSpan (getLoc hs_expr) $ do 	
261
262
263
264
265
266
267
268
269
270
271
272
273
274
	{ level <- getStage
	; case spliceOK level of {
		Nothing 	-> failWithTc (illegalSplice level) ;
		Just next_level -> do 

	{ case level of {
		Comp 		       -> do { (t,k) <- kcTopSpliceType hs_expr 
					     ; return (unLoc t, k) } ;
		Brack _ ps_var lie_var -> do

	{ 	-- A splice inside brackets
	; meta_ty <- tcMetaTy typeQTyConName
	; expr' <- setStage (Splice next_level) $
		   setLIEVar lie_var	   	$
275
		   tcMonoExpr hs_expr meta_ty
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296

		-- Write the pending splice into the bucket
	; ps <- readMutVar ps_var
	; writeMutVar ps_var ((name,expr') : ps)

	-- e.g.   [| Int -> $(h 4) |]
	-- Here (h 4) :: Q Type
	-- but $(h 4) :: forall a.a 	i.e. any kind
	; kind <- newKindVar
	; returnM (panic "kcSpliceType", kind)	-- The returned type is ignored
    }}}}}

kcTopSpliceType :: LHsExpr Name -> TcM (LHsType Name, TcKind)
kcTopSpliceType expr
  = do	{ meta_ty <- tcMetaTy typeQTyConName

	-- Typecheck the expression
	; zonked_q_expr <- tcTopSpliceExpr expr meta_ty

	-- Run the expression
	; traceTc (text "About to run" <+> ppr zonked_q_expr)
297
	; hs_ty2 <- runMetaT convertToHsType zonked_q_expr
298
299
300
301
302
303
304
305
306
307
308
309
310
  
	; traceTc (text "Got result" <+> ppr hs_ty2)

	; showSplice "type" zonked_q_expr (ppr hs_ty2)

	-- Rename it, but bale out if there are errors
	-- otherwise the type checker just gives more spurious errors
	; let doc = ptext SLIT("In the spliced type") <+> ppr hs_ty2
	; hs_ty3 <- checkNoErrs (rnLHsType doc hs_ty2)

	; kcHsType hs_ty3 }
\end{code}

311
312
313
314
315
316
317
318
%************************************************************************
%*									*
\subsection{Splicing an expression}
%*									*
%************************************************************************

\begin{code}
-- Always at top level
319
320
-- Type sig at top of file:
-- 	tcSpliceDecls :: LHsExpr Name -> TcM [LHsDecl RdrName]
321
tcSpliceDecls expr
322
323
324
325
326
327
328
  = do	{ meta_dec_ty <- tcMetaTy decTyConName
	; meta_q_ty <- tcMetaTy qTyConName
	; let list_q = mkAppTy meta_q_ty (mkListTy meta_dec_ty)
	; zonked_q_expr <- tcTopSpliceExpr expr list_q

		-- Run the expression
	; traceTc (text "About to run" <+> ppr zonked_q_expr)
329
	; decls <- runMetaD convertToHsDecls zonked_q_expr
330
331
332

	; traceTc (text "Got result" <+> vcat (map ppr decls))
	; showSplice "declarations"
333
334
	  	     zonked_q_expr 
		     (ppr (getLoc expr) $$ (vcat (map ppr decls)))
335
	; returnM decls }
336
337
338
339
340
341

  where handleErrors :: [Either a Message] -> TcM [a]
        handleErrors [] = return []
        handleErrors (Left x:xs) = liftM (x:) (handleErrors xs)
        handleErrors (Right m:xs) = do addErrTc m
                                       handleErrors xs
342
343
344
345
346
347
348
349
350
351
\end{code}


%************************************************************************
%*									*
\subsection{Running an expression}
%*									*
%************************************************************************

\begin{code}
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
runMetaE :: (SrcSpan -> TH.Exp -> Either Message (LHsExpr RdrName))
	 -> LHsExpr Id 		-- Of type (Q Exp)
	 -> TcM (LHsExpr RdrName)
runMetaE  = runMeta

runMetaT :: (SrcSpan -> TH.Type -> Either Message (LHsType RdrName))
	 -> LHsExpr Id 		-- Of type (Q Type)
	 -> TcM (LHsType RdrName)	
runMetaT = runMeta

runMetaD :: (SrcSpan -> [TH.Dec] -> Either Message [LHsDecl RdrName])
	 -> LHsExpr Id 		-- Of type Q [Dec]
	 -> TcM [LHsDecl RdrName]
runMetaD = runMeta 

runMeta :: (SrcSpan -> th_syn -> Either Message hs_syn)
	-> LHsExpr Id 		-- Of type X
	-> TcM hs_syn		-- Of type t
runMeta convert expr
371
372
373
374
375
  = do	{ hsc_env <- getTopEnv
	; tcg_env <- getGblEnv
	; this_mod <- getModule
	; let type_env = tcg_type_env tcg_env
	      rdr_env  = tcg_rdr_env tcg_env
376
377
378
379

	-- Compile and link it; might fail if linking fails
	; either_hval <- tryM $ ioToTcRn $
			 HscMain.compileExpr 
380
				      hsc_env this_mod 
381
382
383
384
385
386
387
388
			              rdr_env type_env expr
	; case either_hval of {
	    Left exn   -> failWithTc (mk_msg "compile and link" exn) ;
	    Right hval -> do

	{ 	-- Coerce it to Q t, and run it
		-- Running might fail if it throws an exception of any kind (hence tryAllM)
		-- including, say, a pattern-match exception in the code we are running
389
390
391
392
		--
		-- We also do the TH -> HS syntax conversion inside the same
		-- exception-cacthing thing so that if there are any lurking 
		-- exceptions in the data structure returned by hval, we'll
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
393
		-- encounter them inside the try
394
395
396
397
398
	  either_tval <- tryAllM $ do
		{ th_syn <- TH.runQ (unsafeCoerce# hval)
		; case convert (getLoc expr) th_syn of
		    Left err     -> do { addErrTc err; return Nothing }
		    Right hs_syn -> return (Just hs_syn) }
399
400

	; case either_tval of
401
402
403
	      Right (Just v) -> return v
	      Right Nothing  -> failM	-- Error already in Tc monad
	      Left exn       -> failWithTc (mk_msg "run" exn)	-- Exception
404
405
406
407
408
	}}}
  where
    mk_msg s exn = vcat [text "Exception when trying to" <+> text s <+> text "compile-time code:",
			 nest 2 (text (Panic.showException exn)),
			 nest 2 (text "Code:" <+> ppr expr)]
409
410
\end{code}

411
To call runQ in the Tc monad, we need to make TcM an instance of Quasi:
412

413
414
\begin{code}
instance TH.Quasi (IOEnv (Env TcGblEnv TcLclEnv)) where
415
  qNewName s = do { u <- newUnique 
416
417
		  ; let i = getKey u
		  ; return (TH.mkNameU s i) }
418

419
420
  qReport True msg  = addErr (text msg)
  qReport False msg = addReport (text msg)
421

Simon Marlow's avatar
Simon Marlow committed
422
423
424
425
  qCurrentModule = do { m <- getModule;
                        return (moduleNameString (moduleName m)) }
                -- ToDo: is throwing away the package name ok here?

426
  qReify v = reify v
427
428
429
430
431
432
433
434
435
436

	-- For qRecover, discard error messages if 
	-- the recovery action is chosen.  Otherwise
	-- we'll only fail higher up.  c.f. tryTcLIE_
  qRecover recover main = do { (msgs, mb_res) <- tryTcErrs main
			     ; case mb_res of
		  	         Just val -> do { addMessages msgs	-- There might be warnings
				   	        ; return val }
		  	         Nothing  -> recover			-- Discard all msgs
			  }
437

438
439
  qRunIO io = ioToTcRn io
\end{code}
440
441
442
443
444
445
446
447
448


%************************************************************************
%*									*
\subsection{Errors and contexts}
%*									*
%************************************************************************

\begin{code}
449
showSplice :: String -> LHsExpr Id -> SDoc -> TcM ()
450
showSplice what before after
451
  = getSrcSpanM		`thenM` \ loc ->
452
453
454
455
    traceSplice (vcat [ppr loc <> colon <+> text "Splicing" <+> text what, 
		       nest 2 (sep [nest 2 (ppr before),
				    text "======>",
				    nest 2 after])])
456

457
458
459
illegalBracket level
  = ptext SLIT("Illegal bracket at level") <+> ppr level

460
461
462
463
464
illegalSplice level
  = ptext SLIT("Illegal splice at level") <+> ppr level

#endif 	/* GHCI */
\end{code}
465
466
467
468
469
470
471
472
473
474
475


%************************************************************************
%*									*
			Reification
%*									*
%************************************************************************


\begin{code}
reify :: TH.Name -> TcM TH.Info
476
477
reify th_name
  = do	{ name <- lookupThName th_name
478
	; thing <- tcLookupTh name
479
480
		-- ToDo: this tcLookup could fail, which would give a
		-- 	 rather unhelpful error message
481
	; traceIf (text "reify" <+> text (show th_name) <+> brackets (ppr_ns th_name) <+> ppr name)
482
483
	; reifyThing thing
    }
484
  where
Simon Marlow's avatar
Simon Marlow committed
485
486
487
    ppr_ns (TH.Name _ (TH.NameG TH.DataName _pkg _mod)) = text "data"
    ppr_ns (TH.Name _ (TH.NameG TH.TcClsName _pkg _mod)) = text "tc"
    ppr_ns (TH.Name _ (TH.NameG TH.VarName _pkg _mod)) = text "var"
488
489

lookupThName :: TH.Name -> TcM Name
490
491
lookupThName th_name@(TH.Name occ flavour)
  =  do { let rdr_name = thRdrName guessed_ns occ_str flavour
492

493
494
	-- Repeat much of lookupOccRn, becase we want
	-- to report errors in a TH-relevant way
495
496
	; rdr_env <- getLocalRdrEnv
	; case lookupLocalRdrEnv rdr_env rdr_name of
497
498
499
500
501
502
503
	    Just name -> return name
	    Nothing | not (isSrcRdrName rdr_name)	-- Exact, Orig
		    -> lookupImportedName rdr_name
		    | otherwise				-- Unqual, Qual
		    -> do { 
				  mb_name <- lookupSrcOcc_maybe rdr_name
			  ; case mb_name of
504
			      Just name -> return name
505
506
			      Nothing   -> failWithTc (notInScope th_name) }
	}
507
  where
508
	-- guessed_ns is the name space guessed from looking at the TH name
509
510
511
    guessed_ns | isLexCon (mkFastString occ_str) = OccName.dataName
	       | otherwise			 = OccName.varName
    occ_str = TH.occString occ
512

513
514
515
516
517
518
tcLookupTh :: Name -> TcM TcTyThing
-- This is a specialised version of TcEnv.tcLookup; specialised mainly in that
-- it gives a reify-related error message on failure, whereas in the normal
-- tcLookup, failure is a bug.
tcLookupTh name
  = do	{ (gbl_env, lcl_env) <- getEnvs
519
520
	; case lookupNameEnv (tcl_env lcl_env) name of {
		Just thing -> returnM thing;
521
522
523
524
525
526
527
528
529
		Nothing    -> do
	{ if nameIsLocalOrFrom (tcg_mod gbl_env) name
	  then	-- It's defined in this module
	      case lookupNameEnv (tcg_type_env gbl_env) name of
		Just thing -> return (AGlobal thing)
		Nothing	   -> failWithTc (notInEnv name)
	 
	  else do 		-- It's imported
	{ (eps,hpt) <- getEpsAndHpt
Simon Marlow's avatar
Simon Marlow committed
530
531
        ; dflags <- getDOpts
	; case lookupType dflags hpt (eps_PTE eps) name of 
532
	    Just thing -> return (AGlobal thing)
533
	    Nothing    -> do { thing <- tcImportDecl name
534
535
536
			     ; return (AGlobal thing) }
		-- Imported names should always be findable; 
		-- if not, we fail hard in tcImportDecl
537
    }}}}
538

539
notInScope :: TH.Name -> SDoc
540
notInScope th_name = quotes (text (TH.pprint th_name)) <+> 
541
542
543
		     ptext SLIT("is not in scope at a reify")
	-- Ugh! Rather an indirect way to display the name

544
545
546
547
notInEnv :: Name -> SDoc
notInEnv name = quotes (ppr name) <+> 
		     ptext SLIT("is not in the type environment at a reify")

548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
------------------------------
reifyThing :: TcTyThing -> TcM TH.Info
-- The only reason this is monadic is for error reporting,
-- which in turn is mainly for the case when TH can't express
-- some random GHC extension

reifyThing (AGlobal (AnId id))
  = do	{ ty <- reifyType (idType id)
	; fix <- reifyFixity (idName id)
	; let v = reifyName id
	; case globalIdDetails id of
	    ClassOpId cls    -> return (TH.ClassOpI v ty (reifyName cls) fix)
	    other	     -> return (TH.VarI     v ty Nothing fix)
    }

563
564
reifyThing (AGlobal (ATyCon tc))  = reifyTyCon tc
reifyThing (AGlobal (AClass cls)) = reifyClass cls
565
566
567
568
569
570
reifyThing (AGlobal (ADataCon dc))
  = do	{ let name = dataConName dc
	; ty <- reifyType (idType (dataConWrapId dc))
	; fix <- reifyFixity name
	; return (TH.DataConI (reifyName name) ty (reifyName (dataConTyCon dc)) fix) }

571
reifyThing (ATcId id _ _) 
572
573
574
575
576
577
  = do	{ ty1 <- zonkTcType (idType id)	-- Make use of all the info we have, even
					-- though it may be incomplete
	; ty2 <- reifyType ty1
	; fix <- reifyFixity (idName id)
	; return (TH.VarI (reifyName id) ty2 Nothing fix) }

578
579
reifyThing (ATyVar tv ty) 
  = do	{ ty1 <- zonkTcType ty
580
581
582
583
	; ty2 <- reifyType ty1
	; return (TH.TyVarI (reifyName tv) ty2) }

------------------------------
584
reifyTyCon :: TyCon -> TcM TH.Info
585
reifyTyCon tc
586
587
  | isFunTyCon tc  = return (TH.PrimTyConI (reifyName tc) 2 		  False)
  | isPrimTyCon tc = return (TH.PrimTyConI (reifyName tc) (tyConArity tc) (isUnLiftedTyCon tc))
588
  | isSynTyCon tc
589
  = do	{ let (tvs, rhs) = synTyConDefn tc
590
	; rhs' <- reifyType rhs
591
	; return (TH.TyConI $ TH.TySynD (reifyName tc) (reifyTyVars tvs) rhs') }
592

593
reifyTyCon tc
594
595
596
597
598
599
600
601
  = do 	{ cxt <- reifyCxt (tyConStupidTheta tc)
	; cons <- mapM reifyDataCon (tyConDataCons tc)
	; let name = reifyName tc
	      tvs  = reifyTyVars (tyConTyVars tc)
	      deriv = []	-- Don't know about deriving
	      decl | isNewTyCon tc = TH.NewtypeD cxt name tvs (head cons) deriv
		   | otherwise	   = TH.DataD    cxt name tvs cons 	  deriv
	; return (TH.TyConI decl) }
602
603
604

reifyDataCon :: DataCon -> TcM TH.Con
reifyDataCon dc
605
  | isVanillaDataCon dc
606
607
608
  = do 	{ arg_tys <- reifyTypes (dataConOrigArgTys dc)
	; let stricts = map reifyStrict (dataConStrictMarks dc)
	      fields  = dataConFieldLabels dc
609
610
611
612
613
614
	      name    = reifyName dc
	      [a1,a2] = arg_tys
	      [s1,s2] = stricts
	; ASSERT( length arg_tys == length stricts )
          if not (null fields) then
	     return (TH.RecC name (zip3 (map reifyName fields) stricts arg_tys))
615
	  else
616
617
	  if dataConIsInfix dc then
	     ASSERT( length arg_tys == 2 )
618
	     return (TH.InfixC (s1,a1) name (s2,a2))
619
620
	  else
	     return (TH.NormalC name (stricts `zip` arg_tys)) }
621
622
623
  | otherwise
  = failWithTc (ptext SLIT("Can't reify a non-Haskell-98 data constructor:") 
		<+> quotes (ppr dc))
624
625

------------------------------
626
reifyClass :: Class -> TcM TH.Info
627
628
629
reifyClass cls 
  = do	{ cxt <- reifyCxt theta
	; ops <- mapM reify_op op_stuff
630
	; return (TH.ClassI $ TH.ClassD cxt (reifyName cls) (reifyTyVars tvs) fds' ops) }
631
  where
632
633
    (tvs, fds, theta, _, op_stuff) = classExtraBigSig cls
    fds' = map reifyFunDep fds
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
    reify_op (op, _) = do { ty <- reifyType (idType op)
			  ; return (TH.SigD (reifyName op) ty) }

------------------------------
reifyType :: TypeRep.Type -> TcM TH.Type
reifyType (TyVarTy tv)	    = return (TH.VarT (reifyName tv))
reifyType (TyConApp tc tys) = reify_tc_app (reifyName tc) tys
reifyType (NoteTy _ ty)     = reifyType ty
reifyType (AppTy t1 t2)     = do { [r1,r2] <- reifyTypes [t1,t2] ; return (r1 `TH.AppT` r2) }
reifyType (FunTy t1 t2)     = do { [r1,r2] <- reifyTypes [t1,t2] ; return (TH.ArrowT `TH.AppT` r1 `TH.AppT` r2) }
reifyType ty@(ForAllTy _ _) = do { cxt' <- reifyCxt cxt; 
				 ; tau' <- reifyType tau 
				 ; return (TH.ForallT (reifyTyVars tvs) cxt' tau') }
			    where
				(tvs, cxt, tau) = tcSplitSigmaTy ty
reifyTypes = mapM reifyType
reifyCxt   = mapM reifyPred

652
653
654
reifyFunDep :: ([TyVar], [TyVar]) -> TH.FunDep
reifyFunDep (xs, ys) = TH.FunDep (map reifyName xs) (map reifyName ys)

655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
reifyTyVars :: [TyVar] -> [TH.Name]
reifyTyVars = map reifyName

reify_tc_app :: TH.Name -> [TypeRep.Type] -> TcM TH.Type
reify_tc_app tc tys = do { tys' <- reifyTypes tys 
			 ; return (foldl TH.AppT (TH.ConT tc) tys') }

reifyPred :: TypeRep.PredType -> TcM TH.Type
reifyPred (ClassP cls tys) = reify_tc_app (reifyName cls) tys
reifyPred p@(IParam _ _)   = noTH SLIT("implicit parameters") (ppr p)


------------------------------
reifyName :: NamedThing n => n -> TH.Name
reifyName thing
Simon Marlow's avatar
Simon Marlow committed
670
  | isExternalName name = mk_varg pkg_str mod_str occ_str
671
  | otherwise	        = TH.mkNameU occ_str (getKey (getUnique name))
672
673
674
675
	-- Many of the things we reify have local bindings, and 
	-- NameL's aren't supposed to appear in binding positions, so
	-- we use NameU.  When/if we start to reify nested things, that
	-- have free variables, we may need to generate NameL's for them.
676
677
  where
    name    = getName thing
Simon Marlow's avatar
Simon Marlow committed
678
679
680
    mod     = nameModule name
    pkg_str = packageIdString (modulePackageId mod)
    mod_str = moduleNameString (moduleName mod)
681
    occ_str = occNameString occ
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
    occ     = nameOccName name
    mk_varg | OccName.isDataOcc occ = TH.mkNameG_d
	    | OccName.isVarOcc  occ = TH.mkNameG_v
	    | OccName.isTcOcc   occ = TH.mkNameG_tc
	    | otherwise		    = pprPanic "reifyName" (ppr name)

------------------------------
reifyFixity :: Name -> TcM TH.Fixity
reifyFixity name
  = do	{ fix <- lookupFixityRn name
	; return (conv_fix fix) }
    where
      conv_fix (BasicTypes.Fixity i d) = TH.Fixity i (conv_dir d)
      conv_dir BasicTypes.InfixR = TH.InfixR
      conv_dir BasicTypes.InfixL = TH.InfixL
      conv_dir BasicTypes.InfixN = TH.InfixN

reifyStrict :: BasicTypes.StrictnessMark -> TH.Strict
reifyStrict MarkedStrict    = TH.IsStrict
reifyStrict MarkedUnboxed   = TH.IsStrict
reifyStrict NotMarkedStrict = TH.NotStrict

------------------------------
noTH :: LitString -> SDoc -> TcM a
noTH s d = failWithTc (hsep [ptext SLIT("Can't represent") <+> ptext s <+> 
				ptext SLIT("in Template Haskell:"),
		 	     nest 2 d])
709
\end{code}