DsMeta.hs 62.9 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
import MatchLit	  ( dsLit )
25
import DsUtils    ( mkListExpr, mkStringExpr, 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 ( isBoxed ) 
55
import Packages	  ( thPackage )
56
import Outputable
57
import Bag	  ( bagToList )
58
59
60
import FastString ( unpackFS )
import ForeignCall ( Safety(..), ForeignCall(..), CCallConv(..),
                     CCallTarget(..) )
61
62

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

71
72
dsBracket brack splices
  = dsExtendMetaEnv new_bit (do_brack brack)
73
  where
74
    new_bit = mkNameEnv [(n, Splice (unLoc e)) | (n,e) <- splices]
75

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

{- -------------- 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))
-}


97
98
99
100
-------------------------------------------------------
-- 			Declarations
-------------------------------------------------------

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

106
107
108
109
110
	-- 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
111
	-- only "T", not "Foo:T" where Foo is the current module
112
113

	
114
	decls <- addBinds ss (do {
115
116
			val_ds  <- mapM rep_bind_group (hs_valds group) ;
			tycl_ds <- mapM repTyClD (hs_tyclds group) ;
117
			inst_ds <- mapM repInstD' (hs_instds group) ;
118
			for_ds <- mapM repForD (hs_fords group) ;
119
			-- more needed
120
			return (de_loc $ sort_by_loc $ concat val_ds ++ catMaybes tycl_ds ++ inst_ds ++ for_ds) }) ;
121

122
	decl_ty <- lookupType decQTyConName ;
123
	let { core_list = coreList' decl_ty decls } ;
124
125
126

	dec_ty <- lookupType decTyConName ;
	q_decs  <- repSequenceQ dec_ty core_list ;
127
128

	wrapNongenSyms ss q_decs
129
130
131
132
133
	-- Do *not* gensym top-level binders
      }

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


140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
{- 	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" []] []

158
159
So in repTopDs we bring the binders into scope with mkGenSyms and addBinds.
And we use lookupOcc, rather than lookupBinder
160
161
162
163
in repTyClD and repC.

-}

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

166
167
168
169
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] 
170
        dec <- addTyVarBinds tvs $ \bndrs -> do {
171
      	       cxt1    <- repLContext cxt ;
172
               cons1   <- mapM repC cons ;
173
      	       cons2   <- coreList conQTyConName cons1 ;
174
      	       derivs1 <- repDerivs mb_derivs ;
175
176
	       bndrs1  <- coreList nameTyConName bndrs ;
      	       repData cxt1 tc1 bndrs1 cons2 derivs1 } ;
177
        return $ Just (loc, dec) }
178

179
180
181
182
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] 
183
        dec <- addTyVarBinds tvs $ \bndrs -> do {
184
      	       cxt1   <- repLContext cxt ;
185
186
               con1   <- repC con ;
      	       derivs1 <- repDerivs mb_derivs ;
187
188
	       bndrs1  <- coreList nameTyConName bndrs ;
      	       repNewtype cxt1 tc1 bndrs1 con1 derivs1 } ;
189
190
        return $ Just (loc, dec) }

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

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

-- Un-handled cases
214
repTyClD (L loc d) = do { dsWarn (loc, hang ds_msg 4 (ppr d)) ;
215
216
	          	   return Nothing
	     		 }
217

218

219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
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 }

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

238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
repForD :: Located (ForeignDecl Name) -> DsM (SrcSpan, Core TH.DecQ)
repForD (L loc (ForeignImport name typ (CImport cc s ch cn cis) _))
 = do MkC name' <- lookupLOcc name
      MkC typ' <- repLTy typ
      MkC cc' <- repCCallConv cc
      MkC s' <- repSafety s
      MkC str <- coreStringLit $ static
                              ++ unpackFS ch ++ " "
                              ++ unpackFS cn ++ " "
                              ++ conv_cimportspec cis
      dec <- rep2 forImpDName [cc', s', str, name', typ']
      return (loc, dec)
 where
    conv_cimportspec (CLabel cls) = panic "repForD': CLabel Not handled"
    conv_cimportspec (CFunction DynamicTarget) = "dynamic"
    conv_cimportspec (CFunction (StaticTarget fs)) = unpackFS fs
    conv_cimportspec CWrapper = "wrapper"
    static = case cis of
                 CFunction (StaticTarget _) -> "static "
                 _ -> ""

repCCallConv :: CCallConv -> DsM (Core TH.Callconv)
repCCallConv CCallConv = rep2 cCallName []
repCCallConv StdCallConv = rep2 stdCallName []

repSafety :: Safety -> DsM (Core TH.Safety)
repSafety PlayRisky = rep2 unsafeName []
repSafety (PlaySafe False) = rep2 safeName []
repSafety (PlaySafe True) = rep2 threadsafeName []

268
269
ds_msg = ptext SLIT("Cannot desugar this Template Haskell declaration:")

270
271
272
273
-------------------------------------------------------
-- 			Constructors
-------------------------------------------------------

274
275
repC :: LConDecl Name -> DsM (Core TH.ConQ)
repC (L loc (ConDecl con [] (L _ []) details))
276
  = do { con1 <- lookupLOcc con ;		-- See note [Binders and occurrences] 
277
	 repConstr con1 details }
278
279
280
281
282
283
284
285
repC (L loc (ConDecl con tvs (L cloc ctxt) details))
  = do { addTyVarBinds tvs $ \bndrs -> do {
             c' <- repC (L loc (ConDecl con [] (L cloc []) details));
             ctxt' <- repContext ctxt;
             bndrs' <- coreList nameTyConName bndrs;
             rep2 forallCName [unC bndrs', unC ctxt', unC c']
         }
       }
286
287
288
289
repC (L loc con_decl)
  = do	{ dsWarn (loc, hang ds_msg 4 (ppr con_decl))
	; return (panic "DsMeta:repC") }
  where
290
-- gaw 2004 FIX! Need a case for GadtDecl
291

292
repBangTy :: LBangType Name -> DsM (Core (TH.StrictTypeQ))
293
294
295
repBangTy ty= do 
  MkC s <- rep2 str []
  MkC t <- repLTy ty'
296
  rep2 strictTypeName [s, t]
297
298
299
300
  where 
    (str, ty') = case ty of
		   L _ (HsBangTy _ ty) -> (isStrictName,  ty)
		   other	       -> (notStrictName, ty)
301
302
303
304
305

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

306
repDerivs :: Maybe [LHsType Name] -> DsM (Core [TH.Name])
307
repDerivs Nothing = coreList nameTyConName []
308
repDerivs (Just ctxt)
309
  = do { strs <- mapM rep_deriv ctxt ; 
310
	 coreList nameTyConName strs }
311
  where
312
    rep_deriv :: LHsType Name -> DsM (Core TH.Name)
313
	-- Deriving clauses must have the simple H98 form
314
315
    rep_deriv (L _ (HsPredTy (HsClassP cls []))) = lookupOcc cls
    rep_deriv other		  		 = panic "rep_deriv"
316
317
318
319
320
321


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

322
rep_sigs :: [LSig Name] -> DsM [Core TH.DecQ]
323
324
325
rep_sigs sigs = do locs_cores <- rep_sigs' sigs
                   return $ de_loc $ sort_by_loc locs_cores

326
rep_sigs' :: [LSig Name] -> DsM [(SrcSpan, Core TH.DecQ)]
327
	-- We silently ignore ones we don't recognise
328
rep_sigs' sigs = do { sigs1 <- mapM rep_sig sigs ;
329
330
		     return (concat sigs1) }

331
rep_sig :: LSig Name -> DsM [(SrcSpan, Core TH.DecQ)]
332
333
	-- Singleton => Ok
	-- Empty     => Too hard, signature ignored
334
335
rep_sig (L loc (Sig nm ty)) = rep_proto nm ty loc
rep_sig other		    = return []
336

337
338
339
rep_proto :: Located Name -> LHsType Name -> SrcSpan -> DsM [(SrcSpan, Core TH.DecQ)]
rep_proto nm ty loc = do { nm1 <- lookupLOcc nm ; 
		       ty1 <- repLTy ty ; 
340
		       sig <- repProto nm1 ty1 ;
341
		       return [(loc, sig)] }
342
343
344
345
346


-------------------------------------------------------
-- 			Types
-------------------------------------------------------
347

chak's avatar
chak committed
348
349
-- 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
350
-- meta environment and gets the *new* names on Core-level as an argument
chak's avatar
chak committed
351
--
352
addTyVarBinds :: [LHsTyVarBndr Name]	         -- the binders to be added
353
354
	      -> ([Core TH.Name] -> DsM (Core (TH.Q a))) -- action in the ext env
	      -> DsM (Core (TH.Q a))
355
addTyVarBinds tvs m =
chak's avatar
chak committed
356
  do
357
    let names = map (hsTyVarName.unLoc) tvs
358
    freshNames <- mkGenSyms names
chak's avatar
chak committed
359
360
361
    term       <- addBinds freshNames $ do
		    bndrs <- mapM lookupBinder names 
		    m bndrs
362
    wrapGenSyns freshNames term
chak's avatar
chak committed
363

chak's avatar
chak committed
364
365
-- represent a type context
--
366
367
368
repLContext :: LHsContext Name -> DsM (Core TH.CxtQ)
repLContext (L _ ctxt) = repContext ctxt

369
repContext :: HsContext Name -> DsM (Core TH.CxtQ)
chak's avatar
chak committed
370
repContext ctxt = do 
371
	            preds    <- mapM repLPred ctxt
372
		    predList <- coreList typeQTyConName preds
chak's avatar
chak committed
373
		    repCtxt predList
374

chak's avatar
chak committed
375
376
-- represent a type predicate
--
377
378
379
repLPred :: LHsPred Name -> DsM (Core TH.TypeQ)
repLPred (L _ p) = repPred p

380
repPred :: HsPred Name -> DsM (Core TH.TypeQ)
chak's avatar
chak committed
381
382
repPred (HsClassP cls tys) = do
			       tcon <- repTy (HsTyVar cls)
383
			       tys1 <- repLTys tys
chak's avatar
chak committed
384
385
386
387
388
389
			       repTapps tcon tys1
repPred (HsIParam _ _)     = 
  panic "DsMeta.repTy: Can't represent predicates with implicit parameters"

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

chak's avatar
chak committed
393
394
-- represent a type
--
395
396
397
repLTy :: LHsType Name -> DsM (Core TH.TypeQ)
repLTy (L _ ty) = repTy ty

398
399
400
repTy :: HsType Name -> DsM (Core TH.TypeQ)
repTy (HsForAllTy _ tvs ctxt ty)  = 
  addTyVarBinds tvs $ \bndrs -> do
401
402
    ctxt1  <- repLContext ctxt
    ty1    <- repLTy ty
403
404
    bndrs1 <- coreList nameTyConName bndrs
    repTForall bndrs1 ctxt1 ty1
405

406
repTy (HsTyVar n)
chak's avatar
chak committed
407
408
409
410
411
412
413
  | isTvOcc (nameOccName n)       = do 
				      tv1 <- lookupBinder n
				      repTvar tv1
  | otherwise		          = do 
				      tc1 <- lookupOcc n
				      repNamedTyCon tc1
repTy (HsAppTy f a)               = do 
414
415
				      f1 <- repLTy f
				      a1 <- repLTy a
chak's avatar
chak committed
416
417
				      repTapp f1 a1
repTy (HsFunTy f a)               = do 
418
419
				      f1   <- repLTy f
				      a1   <- repLTy a
chak's avatar
chak committed
420
421
422
				      tcon <- repArrowTyCon
				      repTapps tcon [f1, a1]
repTy (HsListTy t)		  = do
423
				      t1   <- repLTy t
chak's avatar
chak committed
424
425
426
				      tcon <- repListTyCon
				      repTapp tcon t1
repTy (HsPArrTy t)                = do
427
				      t1   <- repLTy t
428
				      tcon <- repTy (HsTyVar (tyConName parrTyCon))
chak's avatar
chak committed
429
430
				      repTapp tcon t1
repTy (HsTupleTy tc tys)	  = do
431
				      tys1 <- repLTys tys 
chak's avatar
chak committed
432
433
				      tcon <- repTupleTyCon (length tys)
				      repTapps tcon tys1
434
435
436
repTy (HsOpTy ty1 n ty2) 	  = repLTy ((nlHsTyVar (unLoc n) `nlHsAppTy` ty1) 
					   `nlHsAppTy` ty2)
repTy (HsParTy t)  	       	  = repLTy t
chak's avatar
chak committed
437
438
repTy (HsNumTy i)                 =
  panic "DsMeta.repTy: Can't represent number types (for generics)"
439
repTy (HsPredTy pred)             = repPred pred
chak's avatar
chak committed
440
441
repTy (HsKindSig ty kind)	  = 
  panic "DsMeta.repTy: Can't represent explicit kind signatures yet"
442
443


chak's avatar
chak committed
444
-----------------------------------------------------------------------------
445
-- 		Expressions
chak's avatar
chak committed
446
-----------------------------------------------------------------------------
447

448
449
450
repLEs :: [LHsExpr Name] -> DsM (Core [TH.ExpQ])
repLEs es = do { es'  <- mapM repLE es ;
		 coreList expQTyConName es' }
451

chak's avatar
chak committed
452
453
454
-- 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
455
456
457
repLE :: LHsExpr Name -> DsM (Core TH.ExpQ)
repLE (L _ e) = repE e

458
repE :: HsExpr Name -> DsM (Core TH.ExpQ)
chak's avatar
chak committed
459
460
461
repE (HsVar x)            =
  do { mb_val <- dsLookupMetaEnv x 
     ; case mb_val of
chak's avatar
chak committed
462
	Nothing	         -> do { str <- globalVar x
chak's avatar
chak committed
463
464
465
466
			       ; repVarOrCon x str }
	Just (Bound y)   -> repVarOrCon x (coreVar y)
	Just (Splice e)  -> do { e' <- dsExpr e
			       ; return (MkC e') } }
467
repE (HsIPVar x) = panic "DsMeta.repE: Can't represent implicit parameters"
468
469
470
471
472

	-- 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 }
473
repE (HsLam (MatchGroup [m] _)) = repLambda m
474
repE (HsApp x y)   = do {a <- repLE x; b <- repLE y; repApp a b}
475

chak's avatar
chak committed
476
repE (OpApp e1 op fix e2) =
477
478
479
  do { arg1 <- repLE e1; 
       arg2 <- repLE e2; 
       the_op <- repLE op ;
480
       repInfixApp arg1 the_op arg2 } 
chak's avatar
chak committed
481
repE (NegApp x nm)        = do
482
			      a         <- repLE x
chak's avatar
chak committed
483
484
			      negateVar <- lookupOcc negateName >>= repVar
			      negateVar `repApp` a
485
486
487
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 } 
488
489
490
repE (HsCase e (MatchGroup ms _)) = do { arg <- repLE e
				       ; ms2 <- mapM repMatchTup ms
				       ; repCaseE arg (nonEmptyCoreList ms2) }
491
492
493
494
repE (HsIf x y z)         = do
			      a <- repLE x
			      b <- repLE y
			      c <- repLE z
chak's avatar
chak committed
495
496
			      repCond a b c
repE (HsLet bs e)         = do { (ss,ds) <- repBinds bs
497
			       ; e2 <- addBinds ss (repLE e)
chak's avatar
chak committed
498
			       ; z <- repLetE ds e2
499
			       ; wrapGenSyns ss z }
chak's avatar
chak committed
500
-- FIXME: I haven't got the types here right yet
501
502
repE (HsDo DoExpr sts _ ty) 
 = do { (ss,zs) <- repLSts sts; 
503
        e       <- repDoE (nonEmptyCoreList zs);
504
        wrapGenSyns ss e }
505
506
repE (HsDo ListComp sts _ ty) 
 = do { (ss,zs) <- repLSts sts; 
507
        e       <- repComp (nonEmptyCoreList zs);
508
        wrapGenSyns ss e }
509
510
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
511
512
513
repE (ExplicitPArr ty es) = 
  panic "DsMeta.repE: No explicit parallel arrays yet"
repE (ExplicitTuple es boxed) 
514
  | isBoxed boxed         = do { xs <- repLEs es; repTup xs }
chak's avatar
chak committed
515
  | otherwise		  = panic "DsMeta.repE: Can't represent unboxed tuples"
516
repE (RecordCon c flds)
517
 = do { x <- lookupLOcc c;
518
519
520
        fs <- repFields flds;
        repRecCon x fs }
repE (RecordUpd e flds)
521
 = do { x <- repLE e;
522
523
        fs <- repFields flds;
        repRecUpd x fs }
524

525
repE (ExprWithTySig e ty) = do { e1 <- repLE e; t1 <- repLTy ty; repSigExp e1 t1 }
526
repE (ArithSeqIn aseq) =
chak's avatar
chak committed
527
  case aseq of
528
    From e              -> do { ds1 <- repLE e; repFrom ds1 }
chak's avatar
chak committed
529
    FromThen e1 e2      -> do 
530
531
		             ds1 <- repLE e1
			     ds2 <- repLE e2
chak's avatar
chak committed
532
533
			     repFromThen ds1 ds2
    FromTo   e1 e2      -> do 
534
535
			     ds1 <- repLE e1
			     ds2 <- repLE e2
chak's avatar
chak committed
536
537
			     repFromTo ds1 ds2
    FromThenTo e1 e2 e3 -> do 
538
539
540
			     ds1 <- repLE e1
			     ds2 <- repLE e2
			     ds3 <- repLE e3
chak's avatar
chak committed
541
542
			     repFromThenTo ds1 ds2 ds3
repE (PArrSeqOut _ aseq)  = panic "DsMeta.repE: parallel array seq.s missing"
543
repE (HsCoreAnn _ _)      = panic "DsMeta.repE: Can't represent CoreAnn" -- hdaume: core annotations
chak's avatar
chak committed
544
repE (HsSCC _ _)          = panic "DsMeta.repE: Can't represent SCC"
545
546
547
548
549
550
551
552
553
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)
554
555
556
557

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

558
repMatchTup ::  LMatch Name -> DsM (Core TH.MatchQ) 
559
repMatchTup (L _ (Match [p] ty (GRHSs guards wheres))) =
560
  do { ss1 <- mkGenSyms (collectPatBinders p) 
561
     ; addBinds ss1 $ do {
562
     ; p1 <- repLP p
563
     ; (ss2,ds) <- repBinds wheres
564
565
566
     ; addBinds ss2 $ do {
     ; gs    <- repGuards guards
     ; match <- repMatch p1 gs ds
567
     ; wrapGenSyns (ss1++ss2) match }}}
568

569
repClauseTup ::  LMatch Name -> DsM (Core TH.ClauseQ)
570
repClauseTup (L _ (Match ps ty (GRHSs guards wheres))) =
571
  do { ss1 <- mkGenSyms (collectPatsBinders ps) 
572
     ; addBinds ss1 $ do {
573
       ps1 <- repLPs ps
574
     ; (ss2,ds) <- repBinds wheres
575
576
577
     ; addBinds ss2 $ do {
       gs <- repGuards guards
     ; clause <- repClause ps1 gs ds
578
     ; wrapGenSyns (ss1++ss2) clause }}}
579

580
581
582
repGuards ::  [LGRHS Name] ->  DsM (Core TH.BodyQ)
repGuards [L _ (GRHS [L _ (ResultStmt e)])]
  = do {a <- repLE e; repNormal a }
583
repGuards other 
584
585
586
587
  = do { zs <- mapM process other;
     let {(xs, ys) = unzip zs};
	 gd <- repGuarded (nonEmptyCoreList ys);
     wrapGenSyns (concat xs) gd }
588
  where 
589
590
    process :: LGRHS Name -> DsM ([GenSymBind], (Core (TH.Q (TH.Guard, TH.Exp))))
    process (L _ (GRHS [])) = panic "No guards in guarded body"
591
592
    process (L _ (GRHS [L _ (ExprStmt e1 ty),
			L _ (ResultStmt e2)]))
593
594
595
596
597
598
           = do { x <- repLNormalGE e1 e2;
                  return ([], x) }
    process (L _ (GRHS ss))
           = do (gs, ss') <- repLSts ss
                g <- repPatGE (nonEmptyCoreList ss')
                return (gs, g)
599

600
repFields :: [(Located Name, LHsExpr Name)] -> DsM (Core [TH.Q TH.FieldExp])
601
repFields flds = do
602
603
        fnames <- mapM lookupLOcc (map fst flds)
        es <- mapM repLE (map snd flds)
604
605
        fs <- zipWithM repFieldExp fnames es
        coreList fieldExpQTyConName fs
606

607
608
609

-----------------------------------------------------------------------------
-- Representing Stmt's is tricky, especially if bound variables
610
-- shadow each other. Consider:  [| do { x <- f 1; x <- f x; g x } |]
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
-- 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.

633
634
635
repLSts :: [LStmt Name] -> DsM ([GenSymBind], [Core TH.StmtQ])
repLSts stmts = repSts (map unLoc stmts)

636
repSts :: [Stmt Name] -> DsM ([GenSymBind], [Core TH.StmtQ])
637
638
repSts [ResultStmt e] = 
   do { a <- repLE e
639
640
      ; e1 <- repNoBindSt a
      ; return ([], [e1]) }
641
642
repSts (BindStmt p e : ss) =
   do { e2 <- repLE e 
643
      ; ss1 <- mkGenSyms (collectPatBinders p) 
644
      ; addBinds ss1 $ do {
645
      ; p1 <- repLP p; 
646
647
648
649
      ; (ss2,zs) <- repSts ss
      ; z <- repBindSt p1 e2
      ; return (ss1++ss2, z : zs) }}
repSts (LetStmt bs : ss) =
650
   do { (ss1,ds) <- repBinds bs
651
652
653
      ; z <- repLetSt ds
      ; (ss2,zs) <- addBinds ss1 (repSts ss)
      ; return (ss1++ss2, z : zs) } 
654
655
repSts (ExprStmt e ty : ss) =       
   do { e2 <- repLE e
656
657
658
      ; z <- repNoBindSt e2 
      ; (ss2,zs) <- repSts ss
      ; return (ss2, z : zs) }
659
repSts [] = panic "repSts ran out of statements"      
660
661
662
repSts other = panic "Exotic Stmt in meta brackets"      


663
664
665
-----------------------------------------------------------
--			Bindings
-----------------------------------------------------------
666

667
repBinds :: [HsBindGroup Name] -> DsM ([GenSymBind], Core [TH.DecQ]) 
668
repBinds decs
669
 = do	{ let { bndrs = map unLoc (collectGroupBinders decs) }
670
671
672
673
		-- 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
674
	; ss        <- mkGenSyms bndrs
675
	; core      <- addBinds ss (rep_bind_groups decs)
676
677
	; core_list <- coreList decQTyConName core 
	; return (ss, core_list) }
678

679
rep_bind_groups :: [HsBindGroup Name] -> DsM [Core TH.DecQ]
680
-- Assumes: all the binders of the binding are alrady in the meta-env
681
682
683
rep_bind_groups binds = do 
  locs_cores_s <- mapM rep_bind_group binds
  return $ de_loc $ sort_by_loc (concat locs_cores_s)
684

685
rep_bind_group :: HsBindGroup Name -> DsM [(SrcSpan, Core TH.DecQ)]
686
-- Assumes: all the binders of the binding are alrady in the meta-env
687
688
rep_bind_group (HsBindGroup bs sigs _)
 = do { core1 <- mapM rep_bind (bagToList bs)
689
      ;	core2 <- rep_sigs' sigs
690
      ;	return (core1 ++ core2) }
691
rep_bind_group (HsIPBinds _)
692
  = panic "DsMeta:repBinds: can't do implicit parameters"
693

694
rep_binds :: LHsBinds Name -> DsM [Core TH.DecQ]
695
-- Assumes: all the binders of the binding are alrady in the meta-env
696
697
698
rep_binds binds = do 
  locs_cores <- mapM rep_bind (bagToList binds)
  return $ de_loc $ sort_by_loc locs_cores
699

700
rep_bind :: LHsBind Name -> DsM (SrcSpan, Core TH.DecQ)
701
-- Assumes: all the binders of the binding are alrady in the meta-env
702
703
704
705

-- 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
706
rep_bind (L loc (FunBind fn infx (MatchGroup [L _ (Match [] ty (GRHSs guards wheres))] _)))
707
 = do { (ss,wherecore) <- repBinds wheres
708
	; guardcore <- addBinds ss (repGuards guards)
709
710
711
712
713
	; fn'  <- lookupLBinder fn
	; p    <- repPvar fn'
	; ans  <- repVal p guardcore wherecore
	; ans' <- wrapGenSyns ss ans
	; return (loc, ans') }
714

715
rep_bind (L loc (FunBind fn infx (MatchGroup ms _)))
716
 =   do { ms1 <- mapM repClauseTup ms
717
	; fn' <- lookupLBinder fn
718
        ; ans <- repFun fn' (nonEmptyCoreList ms1)
719
        ; return (loc, ans) }
720

721
rep_bind (L loc (PatBind pat (GRHSs guards wheres) ty2))
722
 =   do { patcore <- repLP pat 
723
        ; (ss,wherecore) <- repBinds wheres
724
	; guardcore <- addBinds ss (repGuards guards)
725
726
727
        ; ans  <- repVal patcore guardcore wherecore
	; ans' <- wrapGenSyns ss ans
        ; return (loc, ans') }
728

729
rep_bind (L loc (VarBind v e))
730
 =   do { v' <- lookupBinder v 
731
	; e2 <- repLE e
732
733
        ; x <- repNormal e2
        ; patcore <- repPvar v'
734
	; empty_decls <- coreList decQTyConName [] 
735
        ; ans <- repVal patcore x empty_decls
736
        ; return (srcLocSpan (getSrcLoc v), ans) }
737
738

-----------------------------------------------------------------------------
739
-- Since everything in a Bind is mutually recursive we need rename all
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
-- 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


-----------------------------------------------------------------------------
756
-- GHC allows a more general form of lambda abstraction than specified
757
758
759
760
761
-- 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.  

762
repLambda :: LMatch Name -> DsM (Core TH.ExpQ)
763
repLambda (L _ (Match ps _ (GRHSs [L _ (GRHS [L _ (ResultStmt e)])] [])))
764
 = do { let bndrs = collectPatsBinders ps ;
765
      ; ss  <- mkGenSyms bndrs
766
      ; lam <- addBinds ss (
767
		do { xs <- repLPs ps; body <- repLE e; repLam xs body })
768
      ; wrapGenSyns ss lam }
769
770
771
772
773

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

  
-----------------------------------------------------------------------------
774
--			Patterns
775
776
777
778
779
780
-- 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
781
repLPs :: [LPat Name] -> DsM (Core [TH.PatQ])
782
repLPs ps = do { ps' <- mapM repLP ps ;
783
		 coreList patQTyConName ps' }
784

785
repLP :: LPat Name -> DsM (Core TH.PatQ)
786
repLP (L _ p) = repP p
787

788
repP :: Pat Name -> DsM (Core TH.PatQ)
789
790
791
repP (WildPat _)     = repPwild 
repP (LitPat l)      = do { l2 <- repLiteral l; repPlit l2 }
repP (VarPat x)      = do { x' <- lookupBinder x; repPvar x' }
792
793
794
795
796
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 }
797
repP (ConPatIn dc details)
798
 = do { con_str <- lookupLOcc dc
799
      ; case details of
800
801
802
         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)
803
                            ; fps <- zipWithM (\x y -> rep2 fieldPatName [unC x,unC y]) vs ps
804
                            ; fps' <- coreList fieldPatQTyConName fps
805
                            ; repPrec con_str fps' }
806
807
808
         InfixCon p1 p2 -> do { p1' <- repLP p1;
                                p2' <- repLP p2;
                                repPinfix p1' con_str p2' }
809
   }
810
811
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 }
812
repP (SigPatIn p t)  = do { p' <- repLP p; t' <- repLTy t; repPsig p' t' }
813
814
repP other = panic "Exotic pattern inside meta brackets"

815
816
817
----------------------------------------------------------
-- Declaration ordering helpers

818
sort_by_loc :: [(SrcSpan, a)] -> [(SrcSpan, a)]
819
820
821
sort_by_loc xs = sortBy comp xs
    where comp x y = compare (fst x) (fst y)

822
de_loc :: [(a, b)] -> [b]
823
824
de_loc = map snd

825
826
827
----------------------------------------------------------
--	The meta-environment

chak's avatar
chak committed
828
-- A name/identifier association for fresh names of locally bound entities
829
830
831
832
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
833
-- Generate a fresh name for a locally bound entity
834

835
836
mkGenSyms :: [Name] -> DsM [GenSymBind]
-- We can use the existing name.  For example:
837
838
839
840
841
--	[| \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
842
--
843
844
845
846
847
848
-- 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] }

849
	     
chak's avatar
chak committed
850
addBinds :: [GenSymBind] -> DsM a -> DsM a
851
852
853
-- 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
854
855
856
857
addBinds bs m = dsExtendMetaEnv (mkNameEnv [(n,Bound id) | (n,id) <- bs]) m

-- Look up a locally bound name
--
858
859
860
lookupLBinder :: Located Name -> DsM (Core TH.Name)
lookupLBinder (L _ n) = lookupBinder n

861
lookupBinder :: Name -> DsM (Core TH.Name)
862
863
864
865
866
867
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
868
869
870
871
872
-- 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
--
873
lookupLOcc :: Located Name -> DsM (Core TH.Name)
874
875
-- Lookup an occurrence; it can't be a splice.
-- Use the in-scope bindings if they exist
876
877
878
lookupLOcc (L _ n) = lookupOcc n

lookupOcc :: Name -> DsM (Core TH.Name)
879
880
881
882
883
884
885
886
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) 
    }

887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
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)
910
911
912
913
	   -> DsM Type	-- The type
lookupType tc_name = do { tc <- dsLookupTyCon tc_name ;
		          return (mkGenTyConApp tc []) }

914
wrapGenSyns :: [GenSymBind] 
915
	    -> Core (TH.Q a) -> DsM (Core (TH.Q a))
916
917
918
919
-- wrapGenSyns [(nm1,id1), (nm2,id2)] y 
--	--> bindQ (gensym nm1) (\ id1 -> 
--	    bindQ (gensym nm2 (\ id2 -> 
--	    y))
920

921
wrapGenSyns binds body@(MkC b)
922
923
  = do  { var_ty <- lookupType nameTyConName
	; go var_ty binds }
924
  where
925
926
927
928
929
    [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

930
931
932
933
    go var_ty [] = return body
    go var_ty ((name,id) : binds)
      = do { MkC body'  <- go var_ty binds
	   ; lit_str    <- occNameLit name
934
	   ; gensym_app <- repGensym lit_str
935
	   ; repBindQ var_ty elt_ty 
936
937
		      gensym_app (MkC (Lam id body')) }

938