DsMeta.hs 57.8 KB
Newer Older
1
2
3
4
5
-----------------------------------------------------------------------------
-- The purpose of this module is to transform an HsExpr into a CoreExpr which
-- when evaluated, returns a (Meta.Q Meta.Exp) computation analogous to the
-- input HsExpr. We do this in the DsM monad, which supplies access to
-- CoreExpr's of the "smart constructors" of the Meta.Exp datatype.
6
7
8
9
10
--
-- It also defines a bunch of knownKeyNames, in the same way as is done
-- in prelude/PrelNames.  It's much more convenient to do it here, becuase
-- otherwise we have to recompile PrelNames whenever we add a Name, which is
-- a Royal Pain (triggers other recompilation).
11
12
13
-----------------------------------------------------------------------------


14
15
module DsMeta( dsBracket, 
	       templateHaskellNames, qTyConName, nameTyConName,
16
	       liftName, expQTyConName, decQTyConName, typeQTyConName,
17
18
	       decTyConName, typeTyConName, mkNameG_dName, mkNameG_vName, mkNameG_tcName
	        ) where
19
20
21
22
23

#include "HsVersions.h"

import {-# SOURCE #-}	DsExpr ( dsExpr )

24
25
import MatchLit	  ( dsLit )
import DsUtils    ( mkListExpr, mkStringLit, mkCoreTup, mkIntExpr )
26
27
import DsMonad

28
import qualified Language.Haskell.TH as TH
29

30
import HsSyn
31
import PrelNames  ( rationalTyConName, integerTyConName, negateName )
32
import OccName	  ( isDataOcc, isTvOcc, occNameUserString )
33
34
35
36
-- To avoid clashes with DsMeta.varName we must make a local alias for OccName.varName
-- we do this by removing varName from the import of OccName above, making
-- a qualified instance of OccName and using OccNameAlias.varName where varName
-- ws previously used in this file.
37
import qualified OccName
38

39
import Module	  ( Module, mkModule, mkModuleName, moduleUserString )
40
import Id         ( Id, mkLocalId )
41
import OccName	  ( mkOccFS )
42
43
import Name       ( Name, mkExternalName, localiseName, nameOccName, nameModule, 
		    isExternalName, getSrcLoc )
44
import NameEnv
45
import Type       ( Type, mkGenTyConApp )
46
import TcType	  ( tcTyConAppArgs )
47
48
import TyCon	  ( tyConName )
import TysWiredIn ( parrTyCon )
49
50
import CoreSyn
import CoreUtils  ( exprType )
51
52
import SrcLoc	  ( noSrcLoc, unLoc, Located(..), SrcSpan, srcLocSpan )
import Maybe	  ( catMaybes )
53
import Unique	  ( mkPreludeTyConUnique, mkPreludeMiscIdUnique, getKey, Uniquable(..) )
54
import BasicTypes ( NewOrData(..), isBoxed ) 
55
import Packages	  ( thPackage )
56
import Outputable
57
import Bag	  ( bagToList )
58
59

import Monad ( zipWithM )
60
import List ( sortBy )
61
62
63
 
-----------------------------------------------------------------------------
dsBracket :: HsBracket Name -> [PendingSplice] -> DsM CoreExpr
64
-- Returns a CoreExpr of type TH.ExpQ
65
66
67
-- The quoted thing is parameterised over Name, even though it has
-- been type checked.  We don't want all those type decorations!

68
69
dsBracket brack splices
  = dsExtendMetaEnv new_bit (do_brack brack)
70
  where
71
    new_bit = mkNameEnv [(n, Splice (unLoc e)) | (n,e) <- splices]
72

73
    do_brack (VarBr n)  = do { MkC e1  <- lookupOcc n ; return e1 }
74
75
76
    do_brack (ExpBr e)  = do { MkC e1  <- repLE e     ; return e1 }
    do_brack (PatBr p)  = do { MkC p1  <- repLP p     ; return p1 }
    do_brack (TypBr t)  = do { MkC t1  <- repLTy t     ; return t1 }
77
    do_brack (DecBr ds) = do { MkC ds1 <- repTopDs ds ; return ds1 }
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

{- -------------- Examples --------------------

  [| \x -> x |]
====>
  gensym (unpackString "x"#) `bindQ` \ x1::String ->
  lam (pvar x1) (var x1)


  [| \x -> $(f [| x |]) |]
====>
  gensym (unpackString "x"#) `bindQ` \ x1::String ->
  lam (pvar x1) (f (var x1))
-}


94
95
96
97
-------------------------------------------------------
-- 			Declarations
-------------------------------------------------------

98
repTopDs :: HsGroup Name -> DsM (Core (TH.Q [TH.Dec]))
99
repTopDs group
100
 = do { let { bndrs = map unLoc (groupBinders group) } ;
101
	ss <- mkGenSyms bndrs ;
102

103
104
105
106
107
	-- Bind all the names mainly to avoid repeated use of explicit strings.
	-- Thus	we get
	--	do { t :: String <- genSym "T" ;
	--	     return (Data t [] ...more t's... }
	-- The other important reason is that the output must mention
108
	-- only "T", not "Foo:T" where Foo is the current module
109
110

	
111
	decls <- addBinds ss (do {
112
113
			val_ds  <- mapM rep_bind_group (hs_valds group) ;
			tycl_ds <- mapM repTyClD (hs_tyclds group) ;
114
			inst_ds <- mapM repInstD' (hs_instds group) ;
115
			-- more needed
116
			return (de_loc $ sort_by_loc $ concat val_ds ++ catMaybes tycl_ds ++ inst_ds) }) ;
117

118
	decl_ty <- lookupType decQTyConName ;
119
	let { core_list = coreList' decl_ty decls } ;
120
121
122

	dec_ty <- lookupType decTyConName ;
	q_decs  <- repSequenceQ dec_ty core_list ;
123
124

	wrapNongenSyms ss q_decs
125
126
127
128
129
	-- Do *not* gensym top-level binders
      }

groupBinders (HsGroup { hs_valds = val_decls, hs_tyclds = tycl_decls,
			hs_fords = foreign_decls })
130
-- Collect the binders of a Group
131
132
133
  = collectGroupBinders val_decls ++
    [n | d <- tycl_decls, n <- tyClDeclNames (unLoc d)] ++
    [n | L _ (ForeignImport n _ _ _) <- foreign_decls]
134
135


136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
{- 	Note [Binders and occurrences]
	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we desugar [d| data T = MkT |]
we want to get
	Data "T" [] [Con "MkT" []] []
and *not*
	Data "Foo:T" [] [Con "Foo:MkT" []] []
That is, the new data decl should fit into whatever new module it is
asked to fit in.   We do *not* clone, though; no need for this:
	Data "T79" ....

But if we see this:
	data T = MkT 
	foo = reifyDecl T

then we must desugar to
	foo = Data "Foo:T" [] [Con "Foo:MkT" []] []

154
155
So in repTopDs we bring the binders into scope with mkGenSyms and addBinds.
And we use lookupOcc, rather than lookupBinder
156
157
158
159
in repTyClD and repC.

-}

160
repTyClD :: LTyClDecl Name -> DsM (Maybe (SrcSpan, Core TH.DecQ))
161

162
163
164
165
repTyClD (L loc (TyData { tcdND = DataType, tcdCtxt = cxt, 
		    tcdLName = tc, tcdTyVars = tvs, 
		    tcdCons = cons, tcdDerivs = mb_derivs }))
 = do { tc1 <- lookupLOcc tc ;		-- See note [Binders and occurrences] 
166
        dec <- addTyVarBinds tvs $ \bndrs -> do {
167
      	       cxt1    <- repLContext cxt ;
168
               cons1   <- mapM repC cons ;
169
      	       cons2   <- coreList conQTyConName cons1 ;
170
      	       derivs1 <- repDerivs mb_derivs ;
171
172
	       bndrs1  <- coreList nameTyConName bndrs ;
      	       repData cxt1 tc1 bndrs1 cons2 derivs1 } ;
173
        return $ Just (loc, dec) }
174

175
176
177
178
repTyClD (L loc (TyData { tcdND = NewType, tcdCtxt = cxt, 
		    tcdLName = tc, tcdTyVars = tvs, 
		    tcdCons = [con], tcdDerivs = mb_derivs }))
 = do { tc1 <- lookupLOcc tc ;		-- See note [Binders and occurrences] 
179
        dec <- addTyVarBinds tvs $ \bndrs -> do {
180
      	       cxt1   <- repLContext cxt ;
181
182
               con1   <- repC con ;
      	       derivs1 <- repDerivs mb_derivs ;
183
184
	       bndrs1  <- coreList nameTyConName bndrs ;
      	       repNewtype cxt1 tc1 bndrs1 con1 derivs1 } ;
185
186
        return $ Just (loc, dec) }

187
188
repTyClD (L loc (TySynonym { tcdLName = tc, tcdTyVars = tvs, tcdSynRhs = ty }))
 = do { tc1 <- lookupLOcc tc ;		-- See note [Binders and occurrences] 
189
        dec <- addTyVarBinds tvs $ \bndrs -> do {
190
	       ty1     <- repLTy ty ;
191
192
	       bndrs1  <- coreList nameTyConName bndrs ;
	       repTySyn tc1 bndrs1 ty1 } ;
193
 	return (Just (loc, dec)) }
194

195
repTyClD (L loc (ClassDecl { tcdCtxt = cxt, tcdLName = cls, 
196
197
		      tcdTyVars = tvs, 
		      tcdFDs = [], 	-- We don't understand functional dependencies
198
199
		      tcdSigs = sigs, tcdMeths = meth_binds }))
 = do { cls1 <- lookupLOcc cls ;		-- See note [Binders and occurrences] 
200
    	dec  <- addTyVarBinds tvs $ \bndrs -> do {
201
 		  cxt1   <- repLContext cxt ;
202
 		  sigs1  <- rep_sigs sigs ;
203
 		  binds1 <- rep_binds meth_binds ;
204
 		  decls1 <- coreList decQTyConName (sigs1 ++ binds1) ;
205
206
	          bndrs1 <- coreList nameTyConName bndrs ;
 		  repClass cxt1 cls1 bndrs1 decls1 } ;
207
    	return $ Just (loc, dec) }
208
209

-- Un-handled cases
210
211
212
repTyClD (L loc d) = do { dsWarn (loc, hang msg 4 (ppr d)) ;
	          	   return Nothing
	     		 }
213
214
  where
    msg = ptext SLIT("Cannot desugar this Template Haskell declaration:")
215

216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
repInstD' (L loc (InstDecl ty binds _))		-- Ignore user pragmas for now
 = do	{ i <- addTyVarBinds tvs $ \tv_bndrs ->
		-- We must bring the type variables into scope, so their occurrences
		-- don't fail,  even though the binders don't appear in the resulting 
		-- data structure
		do {  cxt1 <- repContext cxt
		   ; inst_ty1 <- repPred (HsClassP cls tys)
		   ; ss <- mkGenSyms (collectHsBindBinders binds)
		   ; binds1 <- addBinds ss (rep_binds binds)
		   ; decls1 <- coreList decQTyConName binds1
		   ; decls2 <- wrapNongenSyms ss decls1
		   -- wrapNonGenSyms: do not clone the class op names!
		   -- They must be called 'op' etc, not 'op34'
		   ; repInst cxt1 inst_ty1 decls2 }

231
	; return (loc, i)}
232
 where
233
   (tvs, cxt, cls, tys) = splitHsInstDeclTy (unLoc ty)
234
235
236
237
238

-------------------------------------------------------
-- 			Constructors
-------------------------------------------------------

239
240
241
repC :: LConDecl Name -> DsM (Core TH.ConQ)
repC (L loc (ConDecl con [] (L _ []) details))
  = do { con1     <- lookupLOcc con ;		-- See note [Binders and occurrences] 
242
	 repConstr con1 details }
243

244
245
246
247
248
249
repBangTy :: LBangType Name -> DsM (Core (TH.StrictTypeQ))
repBangTy (L _ (BangType str ty)) = do 
  MkC s <- rep2 strName []
  MkC t <- repLTy ty
  rep2 strictTypeName [s, t]
  where strName = case str of
250
251
			HsNoBang -> notStrictName
			other    -> isStrictName
252
253
254
255
256

-------------------------------------------------------
-- 			Deriving clause
-------------------------------------------------------

257
repDerivs :: Maybe (LHsContext Name) -> DsM (Core [TH.Name])
258
repDerivs Nothing = coreList nameTyConName []
259
repDerivs (Just (L _ ctxt))
260
  = do { strs <- mapM rep_deriv ctxt ; 
261
	 coreList nameTyConName strs }
262
  where
263
    rep_deriv :: LHsPred Name -> DsM (Core TH.Name)
264
	-- Deriving clauses must have the simple H98 form
265
266
    rep_deriv (L _ (HsClassP cls [])) = lookupOcc cls
    rep_deriv other		      = panic "rep_deriv"
267
268
269
270
271
272


-------------------------------------------------------
--   Signatures in a class decl, or a group of bindings
-------------------------------------------------------

273
rep_sigs :: [LSig Name] -> DsM [Core TH.DecQ]
274
275
276
rep_sigs sigs = do locs_cores <- rep_sigs' sigs
                   return $ de_loc $ sort_by_loc locs_cores

277
rep_sigs' :: [LSig Name] -> DsM [(SrcSpan, Core TH.DecQ)]
278
	-- We silently ignore ones we don't recognise
279
rep_sigs' sigs = do { sigs1 <- mapM rep_sig sigs ;
280
281
		     return (concat sigs1) }

282
rep_sig :: LSig Name -> DsM [(SrcSpan, Core TH.DecQ)]
283
284
	-- Singleton => Ok
	-- Empty     => Too hard, signature ignored
285
286
rep_sig (L loc (Sig nm ty)) = rep_proto nm ty loc
rep_sig other		    = return []
287

288
289
290
rep_proto :: Located Name -> LHsType Name -> SrcSpan -> DsM [(SrcSpan, Core TH.DecQ)]
rep_proto nm ty loc = do { nm1 <- lookupLOcc nm ; 
		       ty1 <- repLTy ty ; 
291
		       sig <- repProto nm1 ty1 ;
292
		       return [(loc, sig)] }
293
294
295
296
297


-------------------------------------------------------
-- 			Types
-------------------------------------------------------
298

chak's avatar
chak committed
299
300
-- gensym a list of type variables and enter them into the meta environment;
-- the computations passed as the second argument is executed in that extended
chak's avatar
chak committed
301
-- meta environment and gets the *new* names on Core-level as an argument
chak's avatar
chak committed
302
--
303
addTyVarBinds :: [LHsTyVarBndr Name]	         -- the binders to be added
304
305
	      -> ([Core TH.Name] -> DsM (Core (TH.Q a))) -- action in the ext env
	      -> DsM (Core (TH.Q a))
306
addTyVarBinds tvs m =
chak's avatar
chak committed
307
  do
308
    let names = map (hsTyVarName.unLoc) tvs
309
    freshNames <- mkGenSyms names
chak's avatar
chak committed
310
311
312
    term       <- addBinds freshNames $ do
		    bndrs <- mapM lookupBinder names 
		    m bndrs
313
    wrapGenSyns freshNames term
chak's avatar
chak committed
314

chak's avatar
chak committed
315
316
-- represent a type context
--
317
318
319
repLContext :: LHsContext Name -> DsM (Core TH.CxtQ)
repLContext (L _ ctxt) = repContext ctxt

320
repContext :: HsContext Name -> DsM (Core TH.CxtQ)
chak's avatar
chak committed
321
repContext ctxt = do 
322
	            preds    <- mapM repLPred ctxt
323
		    predList <- coreList typeQTyConName preds
chak's avatar
chak committed
324
		    repCtxt predList
325

chak's avatar
chak committed
326
327
-- represent a type predicate
--
328
329
330
repLPred :: LHsPred Name -> DsM (Core TH.TypeQ)
repLPred (L _ p) = repPred p

331
repPred :: HsPred Name -> DsM (Core TH.TypeQ)
chak's avatar
chak committed
332
333
repPred (HsClassP cls tys) = do
			       tcon <- repTy (HsTyVar cls)
334
			       tys1 <- repLTys tys
chak's avatar
chak committed
335
336
337
338
339
340
			       repTapps tcon tys1
repPred (HsIParam _ _)     = 
  panic "DsMeta.repTy: Can't represent predicates with implicit parameters"

-- yield the representation of a list of types
--
341
342
repLTys :: [LHsType Name] -> DsM [Core TH.TypeQ]
repLTys tys = mapM repLTy tys
343

chak's avatar
chak committed
344
345
-- represent a type
--
346
347
348
repLTy :: LHsType Name -> DsM (Core TH.TypeQ)
repLTy (L _ ty) = repTy ty

349
350
351
repTy :: HsType Name -> DsM (Core TH.TypeQ)
repTy (HsForAllTy _ tvs ctxt ty)  = 
  addTyVarBinds tvs $ \bndrs -> do
352
353
    ctxt1  <- repLContext ctxt
    ty1    <- repLTy ty
354
355
    bndrs1 <- coreList nameTyConName bndrs
    repTForall bndrs1 ctxt1 ty1
356

357
repTy (HsTyVar n)
chak's avatar
chak committed
358
359
360
361
362
363
364
  | isTvOcc (nameOccName n)       = do 
				      tv1 <- lookupBinder n
				      repTvar tv1
  | otherwise		          = do 
				      tc1 <- lookupOcc n
				      repNamedTyCon tc1
repTy (HsAppTy f a)               = do 
365
366
				      f1 <- repLTy f
				      a1 <- repLTy a
chak's avatar
chak committed
367
368
				      repTapp f1 a1
repTy (HsFunTy f a)               = do 
369
370
				      f1   <- repLTy f
				      a1   <- repLTy a
chak's avatar
chak committed
371
372
373
				      tcon <- repArrowTyCon
				      repTapps tcon [f1, a1]
repTy (HsListTy t)		  = do
374
				      t1   <- repLTy t
chak's avatar
chak committed
375
376
377
				      tcon <- repListTyCon
				      repTapp tcon t1
repTy (HsPArrTy t)                = do
378
				      t1   <- repLTy t
379
				      tcon <- repTy (HsTyVar (tyConName parrTyCon))
chak's avatar
chak committed
380
381
				      repTapp tcon t1
repTy (HsTupleTy tc tys)	  = do
382
				      tys1 <- repLTys tys 
chak's avatar
chak committed
383
384
				      tcon <- repTupleTyCon (length tys)
				      repTapps tcon tys1
385
386
387
repTy (HsOpTy ty1 n ty2) 	  = repLTy ((nlHsTyVar (unLoc n) `nlHsAppTy` ty1) 
					   `nlHsAppTy` ty2)
repTy (HsParTy t)  	       	  = repLTy t
chak's avatar
chak committed
388
389
repTy (HsNumTy i)                 =
  panic "DsMeta.repTy: Can't represent number types (for generics)"
390
repTy (HsPredTy pred)             = repLPred pred
chak's avatar
chak committed
391
392
repTy (HsKindSig ty kind)	  = 
  panic "DsMeta.repTy: Can't represent explicit kind signatures yet"
393
394


chak's avatar
chak committed
395
-----------------------------------------------------------------------------
396
-- 		Expressions
chak's avatar
chak committed
397
-----------------------------------------------------------------------------
398

399
400
401
repLEs :: [LHsExpr Name] -> DsM (Core [TH.ExpQ])
repLEs es = do { es'  <- mapM repLE es ;
		 coreList expQTyConName es' }
402

chak's avatar
chak committed
403
404
405
-- FIXME: some of these panics should be converted into proper error messages
--	  unless we can make sure that constructs, which are plainly not
--	  supported in TH already lead to error messages at an earlier stage
406
407
408
repLE :: LHsExpr Name -> DsM (Core TH.ExpQ)
repLE (L _ e) = repE e

409
repE :: HsExpr Name -> DsM (Core TH.ExpQ)
chak's avatar
chak committed
410
411
412
repE (HsVar x)            =
  do { mb_val <- dsLookupMetaEnv x 
     ; case mb_val of
chak's avatar
chak committed
413
	Nothing	         -> do { str <- globalVar x
chak's avatar
chak committed
414
415
416
417
			       ; repVarOrCon x str }
	Just (Bound y)   -> repVarOrCon x (coreVar y)
	Just (Splice e)  -> do { e' <- dsExpr e
			       ; return (MkC e') } }
418
repE (HsIPVar x) = panic "DsMeta.repE: Can't represent implicit parameters"
419
420
421
422
423
424

	-- Remember, we're desugaring renamer output here, so
	-- HsOverlit can definitely occur
repE (HsOverLit l) = do { a <- repOverloadedLiteral l; repLit a }
repE (HsLit l)     = do { a <- repLiteral l;           repLit a }
repE (HsLam m)     = repLambda m
425
repE (HsApp x y)   = do {a <- repLE x; b <- repLE y; repApp a b}
426

chak's avatar
chak committed
427
repE (OpApp e1 op fix e2) =
428
429
430
  do { arg1 <- repLE e1; 
       arg2 <- repLE e2; 
       the_op <- repLE op ;
431
       repInfixApp arg1 the_op arg2 } 
chak's avatar
chak committed
432
repE (NegApp x nm)        = do
433
			      a         <- repLE x
chak's avatar
chak committed
434
435
			      negateVar <- lookupOcc negateName >>= repVar
			      negateVar `repApp` a
436
437
438
439
repE (HsPar x)            = repLE x
repE (SectionL x y)       = do { a <- repLE x; b <- repLE y; repSectionL a b } 
repE (SectionR x y)       = do { a <- repLE x; b <- repLE y; repSectionR a b } 
repE (HsCase e ms)        = do { arg <- repLE e
chak's avatar
chak committed
440
441
			       ; ms2 <- mapM repMatchTup ms
			       ; repCaseE arg (nonEmptyCoreList ms2) }
442
443
444
445
repE (HsIf x y z)         = do
			      a <- repLE x
			      b <- repLE y
			      c <- repLE z
chak's avatar
chak committed
446
447
			      repCond a b c
repE (HsLet bs e)         = do { (ss,ds) <- repBinds bs
448
			       ; e2 <- addBinds ss (repLE e)
chak's avatar
chak committed
449
			       ; z <- repLetE ds e2
450
			       ; wrapGenSyns ss z }
chak's avatar
chak committed
451
-- FIXME: I haven't got the types here right yet
452
453
repE (HsDo DoExpr sts _ ty) 
 = do { (ss,zs) <- repLSts sts; 
454
        e       <- repDoE (nonEmptyCoreList zs);
455
        wrapGenSyns ss e }
456
457
repE (HsDo ListComp sts _ ty) 
 = do { (ss,zs) <- repLSts sts; 
458
        e       <- repComp (nonEmptyCoreList zs);
459
        wrapGenSyns ss e }
460
461
repE (HsDo _ _ _ _) = panic "DsMeta.repE: Can't represent mdo and [: :] yet"
repE (ExplicitList ty es) = do { xs <- repLEs es; repListExp xs } 
chak's avatar
chak committed
462
463
464
repE (ExplicitPArr ty es) = 
  panic "DsMeta.repE: No explicit parallel arrays yet"
repE (ExplicitTuple es boxed) 
465
  | isBoxed boxed         = do { xs <- repLEs es; repTup xs }
chak's avatar
chak committed
466
  | otherwise		  = panic "DsMeta.repE: Can't represent unboxed tuples"
467
repE (RecordCon c flds)
468
 = do { x <- lookupLOcc c;
469
470
471
        fs <- repFields flds;
        repRecCon x fs }
repE (RecordUpd e flds)
472
 = do { x <- repLE e;
473
474
        fs <- repFields flds;
        repRecUpd x fs }
475

476
repE (ExprWithTySig e ty) = do { e1 <- repLE e; t1 <- repLTy ty; repSigExp e1 t1 }
477
repE (ArithSeqIn aseq) =
chak's avatar
chak committed
478
  case aseq of
479
    From e              -> do { ds1 <- repLE e; repFrom ds1 }
chak's avatar
chak committed
480
    FromThen e1 e2      -> do 
481
482
		             ds1 <- repLE e1
			     ds2 <- repLE e2
chak's avatar
chak committed
483
484
			     repFromThen ds1 ds2
    FromTo   e1 e2      -> do 
485
486
			     ds1 <- repLE e1
			     ds2 <- repLE e2
chak's avatar
chak committed
487
488
			     repFromTo ds1 ds2
    FromThenTo e1 e2 e3 -> do 
489
490
491
			     ds1 <- repLE e1
			     ds2 <- repLE e2
			     ds3 <- repLE e3
chak's avatar
chak committed
492
493
			     repFromThenTo ds1 ds2 ds3
repE (PArrSeqOut _ aseq)  = panic "DsMeta.repE: parallel array seq.s missing"
494
repE (HsCoreAnn _ _)      = panic "DsMeta.repE: Can't represent CoreAnn" -- hdaume: core annotations
chak's avatar
chak committed
495
repE (HsSCC _ _)          = panic "DsMeta.repE: Can't represent SCC"
496
497
498
499
500
501
502
503
504
repE (HsBracketOut _ _)   = panic "DsMeta.repE: Can't represent Oxford brackets"
repE (HsSpliceE (HsSplice n _)) 
  = do { mb_val <- dsLookupMetaEnv n
       ; case mb_val of
		 Just (Splice e) -> do { e' <- dsExpr e
				       ; return (MkC e') }
		 other	     -> pprPanic "HsSplice" (ppr n) }

repE e = pprPanic "DsMeta.repE: Illegal expression form" (ppr e)
505
506
507
508

-----------------------------------------------------------------------------
-- Building representations of auxillary structures like Match, Clause, Stmt, 

509
510
repMatchTup ::  LMatch Name -> DsM (Core TH.MatchQ) 
repMatchTup (L _ (Match [p] ty (GRHSs guards wheres ty2))) =
511
  do { ss1 <- mkGenSyms (collectPatBinders p) 
512
     ; addBinds ss1 $ do {
513
     ; p1 <- repLP p
514
     ; (ss2,ds) <- repBinds wheres
515
516
517
     ; addBinds ss2 $ do {
     ; gs    <- repGuards guards
     ; match <- repMatch p1 gs ds
518
     ; wrapGenSyns (ss1++ss2) match }}}
519

520
521
repClauseTup ::  LMatch Name -> DsM (Core TH.ClauseQ)
repClauseTup (L _ (Match ps ty (GRHSs guards wheres ty2))) =
522
  do { ss1 <- mkGenSyms (collectPatsBinders ps) 
523
     ; addBinds ss1 $ do {
524
       ps1 <- repLPs ps
525
     ; (ss2,ds) <- repBinds wheres
526
527
528
     ; addBinds ss2 $ do {
       gs <- repGuards guards
     ; clause <- repClause ps1 gs ds
529
     ; wrapGenSyns (ss1++ss2) clause }}}
530

531
532
533
repGuards ::  [LGRHS Name] ->  DsM (Core TH.BodyQ)
repGuards [L _ (GRHS [L _ (ResultStmt e)])]
  = do {a <- repLE e; repNormal a }
534
535
536
537
repGuards other 
  = do { zs <- mapM process other; 
	 repGuarded (nonEmptyCoreList (map corePair zs)) }
  where 
538
539
540
    process (L _ (GRHS [L _ (ExprStmt e1 ty),
			L _ (ResultStmt e2)]))
           = do { x <- repLE e1; y <- repLE e2; return (x, y) }
541
542
    process other = panic "Non Haskell 98 guarded body"

543
repFields :: [(Located Name, LHsExpr Name)] -> DsM (Core [TH.FieldExp])
544
repFields flds = do
545
546
        fnames <- mapM lookupLOcc (map fst flds)
        es <- mapM repLE (map snd flds)
547
548
        fs <- zipWithM (\n x -> rep2 fieldExpName [unC n, unC x]) fnames es
        coreList fieldExpTyConName fs
549

550
551
552

-----------------------------------------------------------------------------
-- Representing Stmt's is tricky, especially if bound variables
553
-- shadow each other. Consider:  [| do { x <- f 1; x <- f x; g x } |]
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
-- First gensym new names for every variable in any of the patterns.
-- both static (x'1 and x'2), and dynamic ((gensym "x") and (gensym "y"))
-- if variables didn't shaddow, the static gensym wouldn't be necessary
-- and we could reuse the original names (x and x).
--
-- do { x'1 <- gensym "x"
--    ; x'2 <- gensym "x"   
--    ; doE [ BindSt (pvar x'1) [| f 1 |]
--          , BindSt (pvar x'2) [| f x |] 
--          , NoBindSt [| g x |] 
--          ]
--    }

-- The strategy is to translate a whole list of do-bindings by building a
-- bigger environment, and a bigger set of meta bindings 
-- (like:  x'1 <- gensym "x" ) and then combining these with the translations
-- of the expressions within the Do
      
-----------------------------------------------------------------------------
-- The helper function repSts computes the translation of each sub expression
-- and a bunch of prefix bindings denoting the dynamic renaming.

576
577
578
repLSts :: [LStmt Name] -> DsM ([GenSymBind], [Core TH.StmtQ])
repLSts stmts = repSts (map unLoc stmts)

579
repSts :: [Stmt Name] -> DsM ([GenSymBind], [Core TH.StmtQ])
580
581
repSts [ResultStmt e] = 
   do { a <- repLE e
582
583
      ; e1 <- repNoBindSt a
      ; return ([], [e1]) }
584
585
repSts (BindStmt p e : ss) =
   do { e2 <- repLE e 
586
      ; ss1 <- mkGenSyms (collectPatBinders p) 
587
      ; addBinds ss1 $ do {
588
      ; p1 <- repLP p; 
589
590
591
592
      ; (ss2,zs) <- repSts ss
      ; z <- repBindSt p1 e2
      ; return (ss1++ss2, z : zs) }}
repSts (LetStmt bs : ss) =
593
   do { (ss1,ds) <- repBinds bs
594
595
596
      ; z <- repLetSt ds
      ; (ss2,zs) <- addBinds ss1 (repSts ss)
      ; return (ss1++ss2, z : zs) } 
597
598
repSts (ExprStmt e ty : ss) =       
   do { e2 <- repLE e
599
600
601
602
603
604
      ; z <- repNoBindSt e2 
      ; (ss2,zs) <- repSts ss
      ; return (ss2, z : zs) }
repSts other = panic "Exotic Stmt in meta brackets"      


605
606
607
-----------------------------------------------------------
--			Bindings
-----------------------------------------------------------
608

609
repBinds :: [HsBindGroup Name] -> DsM ([GenSymBind], Core [TH.DecQ]) 
610
repBinds decs
611
 = do	{ let { bndrs = map unLoc (collectGroupBinders decs) }
612
613
614
615
		-- No need to worrry about detailed scopes within
		-- the binding group, because we are talking Names
		-- here, so we can safely treat it as a mutually 
		-- recursive group
616
	; ss        <- mkGenSyms bndrs
617
	; core      <- addBinds ss (rep_bind_groups decs)
618
619
	; core_list <- coreList decQTyConName core 
	; return (ss, core_list) }
620

621
rep_bind_groups :: [HsBindGroup Name] -> DsM [Core TH.DecQ]
622
-- Assumes: all the binders of the binding are alrady in the meta-env
623
624
625
rep_bind_groups binds = do 
  locs_cores_s <- mapM rep_bind_group binds
  return $ de_loc $ sort_by_loc (concat locs_cores_s)
626

627
rep_bind_group :: HsBindGroup Name -> DsM [(SrcSpan, Core TH.DecQ)]
628
-- Assumes: all the binders of the binding are alrady in the meta-env
629
630
rep_bind_group (HsBindGroup bs sigs _)
 = do { core1 <- mapM rep_bind (bagToList bs)
631
      ;	core2 <- rep_sigs' sigs
632
      ;	return (core1 ++ core2) }
633
rep_bind_group (HsIPBinds _)
634
  = panic "DsMeta:repBinds: can't do implicit parameters"
635

636
rep_binds :: LHsBinds Name -> DsM [Core TH.DecQ]
637
-- Assumes: all the binders of the binding are alrady in the meta-env
638
639
640
rep_binds binds = do 
  locs_cores <- mapM rep_bind (bagToList binds)
  return $ de_loc $ sort_by_loc locs_cores
641

642
rep_bind :: LHsBind Name -> DsM (SrcSpan, Core TH.DecQ)
643
-- Assumes: all the binders of the binding are alrady in the meta-env
644
645
646
647

-- Note GHC treats declarations of a variable (not a pattern) 
-- e.g.  x = g 5 as a Fun MonoBinds. This is indicated by a single match 
-- with an empty list of patterns
648
rep_bind (L loc (FunBind fn infx [L _ (Match [] ty (GRHSs guards wheres ty2))]))
649
 = do { (ss,wherecore) <- repBinds wheres
650
	; guardcore <- addBinds ss (repGuards guards)
651
	; fn' <- lookupLBinder fn
652
653
	; p   <- repPvar fn'
	; ans <- repVal p guardcore wherecore
654
	; return (loc, ans) }
655

656
rep_bind (L loc (FunBind fn infx ms))
657
 =   do { ms1 <- mapM repClauseTup ms
658
	; fn' <- lookupLBinder fn
659
        ; ans <- repFun fn' (nonEmptyCoreList ms1)
660
        ; return (loc, ans) }
661

662
663
rep_bind (L loc (PatBind pat (GRHSs guards wheres ty2)))
 =   do { patcore <- repLP pat 
664
        ; (ss,wherecore) <- repBinds wheres
665
666
	; guardcore <- addBinds ss (repGuards guards)
        ; ans <- repVal patcore guardcore wherecore
667
        ; return (loc, ans) }
668

669
rep_bind (L loc (VarBind v e))
670
 =   do { v' <- lookupBinder v 
671
	; e2 <- repLE e
672
673
        ; x <- repNormal e2
        ; patcore <- repPvar v'
674
	; empty_decls <- coreList decQTyConName [] 
675
        ; ans <- repVal patcore x empty_decls
676
        ; return (srcLocSpan (getSrcLoc v), ans) }
677
678

-----------------------------------------------------------------------------
679
-- Since everything in a Bind is mutually recursive we need rename all
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
-- all the variables simultaneously. For example: 
-- [| AndMonoBinds (f x = x + g 2) (g x = f 1 + 2) |] would translate to
-- do { f'1 <- gensym "f"
--    ; g'2 <- gensym "g"
--    ; [ do { x'3 <- gensym "x"; fun f'1 [pvar x'3] [| x + g2 |]},
--        do { x'4 <- gensym "x"; fun g'2 [pvar x'4] [| f 1 + 2 |]}
--      ]}
-- This requires collecting the bindings (f'1 <- gensym "f"), and the 
-- environment ( f |-> f'1 ) from each binding, and then unioning them 
-- together. As we do this we collect GenSymBinds's which represent the renamed 
-- variables bound by the Bindings. In order not to lose track of these 
-- representations we build a shadow datatype MB with the same structure as 
-- MonoBinds, but which has slots for the representations


-----------------------------------------------------------------------------
696
-- GHC allows a more general form of lambda abstraction than specified
697
698
699
700
701
-- by Haskell 98. In particular it allows guarded lambda's like : 
-- (\  x | even x -> 0 | odd x -> 1) at the moment we can't represent this in
-- Haskell Template's Meta.Exp type so we punt if it isn't a simple thing like
-- (\ p1 .. pn -> exp) by causing an error.  

702
703
repLambda :: LMatch Name -> DsM (Core TH.ExpQ)
repLambda (L _ (Match ps _ (GRHSs [L _ (GRHS [L _ (ResultStmt e)])] [] _)))
704
 = do { let bndrs = collectPatsBinders ps ;
705
      ; ss  <- mkGenSyms bndrs
706
      ; lam <- addBinds ss (
707
		do { xs <- repLPs ps; body <- repLE e; repLam xs body })
708
      ; wrapGenSyns ss lam }
709
710
711
712
713

repLambda z = panic "Can't represent a guarded lambda in Template Haskell"  

  
-----------------------------------------------------------------------------
714
--			Patterns
715
716
717
718
719
720
-- repP deals with patterns.  It assumes that we have already
-- walked over the pattern(s) once to collect the binders, and 
-- have extended the environment.  So every pattern-bound 
-- variable should already appear in the environment.

-- Process a list of patterns
721
722
723
724
725
726
repLPs :: [LPat Name] -> DsM (Core [TH.Pat])
repLPs ps = do { ps' <- mapM repLP ps ;
		 coreList patTyConName ps' }

repLP :: LPat Name -> DsM (Core TH.Pat)
repLP (L _ p) = repP p
727

728
repP :: Pat Name -> DsM (Core TH.Pat)
729
730
731
repP (WildPat _)     = repPwild 
repP (LitPat l)      = do { l2 <- repLiteral l; repPlit l2 }
repP (VarPat x)      = do { x' <- lookupBinder x; repPvar x' }
732
733
734
735
736
repP (LazyPat p)     = do { p1 <- repLP p; repPtilde p1 }
repP (AsPat x p)     = do { x' <- lookupLBinder x; p1 <- repLP p; repPaspat x' p1 }
repP (ParPat p)      = repLP p 
repP (ListPat ps _)  = do { qs <- repLPs ps; repPlist qs }
repP (TuplePat ps _) = do { qs <- repLPs ps; repPtup qs }
737
repP (ConPatIn dc details)
738
 = do { con_str <- lookupLOcc dc
739
      ; case details of
740
741
742
         PrefixCon ps   -> do { qs <- repLPs ps; repPcon con_str qs }
         RecCon pairs -> do { vs <- sequence $ map lookupLOcc (map fst pairs)
                            ; ps <- sequence $ map repLP (map snd pairs)
743
744
                            ; fps <- zipWithM (\x y -> rep2 fieldPatName [unC x,unC y]) vs ps
                            ; fps' <- coreList fieldPatTyConName fps
745
                            ; repPrec con_str fps' }
746
         InfixCon p1 p2 -> do { qs <- repLPs [p1,p2]; repPcon con_str qs }
747
   }
748
749
repP (NPatIn l (Just _)) = panic "Can't cope with negative overloaded patterns yet (repP (NPatIn _ (Just _)))"
repP (NPatIn l Nothing) = do { a <- repOverloadedLiteral l; repPlit a }
750
751
repP other = panic "Exotic pattern inside meta brackets"

752
753
754
----------------------------------------------------------
-- Declaration ordering helpers

755
sort_by_loc :: [(SrcSpan, a)] -> [(SrcSpan, a)]
756
757
758
sort_by_loc xs = sortBy comp xs
    where comp x y = compare (fst x) (fst y)

759
de_loc :: [(a, b)] -> [b]
760
761
de_loc = map snd

762
763
764
----------------------------------------------------------
--	The meta-environment

chak's avatar
chak committed
765
-- A name/identifier association for fresh names of locally bound entities
766
767
768
769
type GenSymBind = (Name, Id)	-- Gensym the string and bind it to the Id
				-- I.e.		(x, x_id) means
				--	let x_id = gensym "x" in ...

chak's avatar
chak committed
770
-- Generate a fresh name for a locally bound entity
771

772
773
mkGenSyms :: [Name] -> DsM [GenSymBind]
-- We can use the existing name.  For example:
774
775
776
777
778
--	[| \x_77 -> x_77 + x_77 |]
-- desugars to
--	do { x_77 <- genSym "x"; .... }
-- We use the same x_77 in the desugared program, but with the type Bndr
-- instead of Int
chak's avatar
chak committed
779
--
780
781
782
783
784
785
-- We do make it an Internal name, though (hence localiseName)
--
-- Nevertheless, it's monadic because we have to generate nameTy
mkGenSyms ns = do { var_ty <- lookupType nameTyConName
		  ; return [(nm, mkLocalId (localiseName nm) var_ty) | nm <- ns] }

786
	     
chak's avatar
chak committed
787
addBinds :: [GenSymBind] -> DsM a -> DsM a
788
789
790
-- Add a list of fresh names for locally bound entities to the 
-- meta environment (which is part of the state carried around 
-- by the desugarer monad) 
chak's avatar
chak committed
791
792
793
794
addBinds bs m = dsExtendMetaEnv (mkNameEnv [(n,Bound id) | (n,id) <- bs]) m

-- Look up a locally bound name
--
795
796
797
lookupLBinder :: Located Name -> DsM (Core TH.Name)
lookupLBinder (L _ n) = lookupBinder n

798
lookupBinder :: Name -> DsM (Core TH.Name)
799
800
801
802
803
804
lookupBinder n 
  = do { mb_val <- dsLookupMetaEnv n;
	 case mb_val of
	    Just (Bound x) -> return (coreVar x)
	    other	   -> pprPanic "Failed binder lookup:" (ppr n) }

chak's avatar
chak committed
805
806
807
808
809
-- Look up a name that is either locally bound or a global name
--
-- * If it is a global name, generate the "original name" representation (ie,
--   the <module>:<name> form) for the associated entity
--
810
lookupLOcc :: Located Name -> DsM (Core TH.Name)
811
812
-- Lookup an occurrence; it can't be a splice.
-- Use the in-scope bindings if they exist
813
814
815
lookupLOcc (L _ n) = lookupOcc n

lookupOcc :: Name -> DsM (Core TH.Name)
816
817
818
819
820
821
822
823
lookupOcc n
  = do {  mb_val <- dsLookupMetaEnv n ;
          case mb_val of
		Nothing         -> globalVar n
		Just (Bound x)  -> return (coreVar x)
		Just (Splice _) -> pprPanic "repE:lookupOcc" (ppr n) 
    }

824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
globalVar :: Name -> DsM (Core TH.Name)
-- Not bound by the meta-env
-- Could be top-level; or could be local
--	f x = $(g [| x |])
-- Here the x will be local
globalVar name
  | isExternalName name
  = do	{ MkC mod <- coreStringLit name_mod
	; MkC occ <- occNameLit name
	; rep2 mk_varg [mod,occ] }
  | otherwise
  = do 	{ MkC occ <- occNameLit name
	; MkC uni <- coreIntLit (getKey (getUnique name))
	; rep2 mkNameUName [occ,uni] }
  where
      name_mod = moduleUserString (nameModule name)
      name_occ = nameOccName name
      mk_varg | OccName.isDataOcc name_occ = mkNameG_dName
	      | OccName.isVarOcc  name_occ = mkNameG_vName
	      | OccName.isTcOcc   name_occ = mkNameG_tcName
	      | otherwise 	           = pprPanic "DsMeta.globalVar" (ppr name)

lookupType :: Name 	-- Name of type constructor (e.g. TH.ExpQ)
847
848
849
850
	   -> DsM Type	-- The type
lookupType tc_name = do { tc <- dsLookupTyCon tc_name ;
		          return (mkGenTyConApp tc []) }

851
wrapGenSyns :: [GenSymBind] 
852
	    -> Core (TH.Q a) -> DsM (Core (TH.Q a))
853
854
855
856
-- wrapGenSyns [(nm1,id1), (nm2,id2)] y 
--	--> bindQ (gensym nm1) (\ id1 -> 
--	    bindQ (gensym nm2 (\ id2 -> 
--	    y))
857

858
wrapGenSyns binds body@(MkC b)
859
860
  = do  { var_ty <- lookupType nameTyConName
	; go var_ty binds }
861
  where
862
863
864
865
866
    [elt_ty] = tcTyConAppArgs (exprType b) 
	-- b :: Q a, so we can get the type 'a' by looking at the
	-- argument type. NB: this relies on Q being a data/newtype,
	-- not a type synonym

867
868
869
870
    go var_ty [] = return body
    go var_ty ((name,id) : binds)
      = do { MkC body'  <- go var_ty binds
	   ; lit_str    <- occNameLit name
871
	   ; gensym_app <- repGensym lit_str
872
	   ; repBindQ var_ty elt_ty 
873
874
		      gensym_app (MkC (Lam id body')) }

875
-- Just like wrapGenSym, but don't actually do the gensym
876
877
878
879
-- Instead use the existing name:
--	let x = "x" in ...
-- Only used for [Decl], and for the class ops in class 
-- and instance decls
880
881
882
883
wrapNongenSyms :: [GenSymBind] -> Core a -> DsM (Core a)
wrapNongenSyms binds (MkC body)
  = do { binds' <- mapM do_one binds ;
	 return (MkC (mkLets binds' body)) }
884
  where
885
    do_one (name,id) 
886
887
888
889
890
891
	= do { MkC lit_str <- occNameLit name
	     ; MkC var <- rep2 mkNameName [lit_str]
	     ; return (NonRec id var) }

occNameLit :: Name -> DsM (Core String)
occNameLit n = coreStringLit (occNameUserString (nameOccName n))
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921


-- %*********************************************************************
-- %*									*
--		Constructing code
-- %*									*
-- %*********************************************************************

-----------------------------------------------------------------------------
-- PHANTOM TYPES for consistency. In order to make sure we do this correct 
-- we invent a new datatype which uses phantom types.

newtype Core a = MkC CoreExpr
unC (MkC x) = x

rep2 :: Name -> [ CoreExpr ] -> DsM (Core a)
rep2 n xs = do { id <- dsLookupGlobalId n
               ; return (MkC (foldl App (Var id) xs)) }

-- Then we make "repConstructors" which use the phantom types for each of the
-- smart constructors of the Meta.Meta datatypes.


-- %*********************************************************************
-- %*									*
--		The 'smart constructors'
-- %*									*
-- %*********************************************************************

--------------- Patterns -----------------
922
repPlit   :: Core TH.Lit -> DsM (Core TH.Pat) 
923
repPlit (MkC l) = rep2 litPName [l]
924

925
repPvar :: Core TH.Name -> DsM (Core TH.Pat)
926
repPvar (MkC s) = rep2 varPName [s]
927

928
repPtup :: Core [TH.Pat] -> DsM (Core TH.Pat)
929
repPtup (MkC ps) = rep2 tupPName [ps]
930

931
repPcon   :: Core TH.Name -> Core [TH.Pat] -> DsM (Core TH.Pat)
932
repPcon (MkC s) (MkC ps) = rep2 conPName [s, ps]
933

934
repPrec   :: Core TH.Name -> Core [(TH.Name,TH.Pat)] -> DsM (Core TH.Pat)
935
repPrec (MkC c) (MkC rps) = rep2 recPName [c,rps]
936

937
repPtilde :: Core TH.Pat -> DsM (Core TH.Pat)
938
repPtilde (MkC p) = rep2 tildePName [p]
939

940
repPaspat :: Core TH.Name -> Core TH