DsExpr.lhs 21.9 KB
Newer Older
1
%
2
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3
4
5
6
%
\section[DsExpr]{Matching expressions (Exprs)}

\begin{code}
7
module DsExpr ( dsExpr, dsLExpr, dsLet, dsLit ) where
8

9
10
#include "HsVersions.h"

11

12
13
import Match		( matchWrapper, matchSimply )
import MatchLit		( dsLit )
14
import DsBinds		( dsHsBinds, AutoScc(..) )
15
16
import DsGRHSs		( dsGuarded )
import DsListComp	( dsListComp, dsPArrComp )
17
import DsUtils		( mkErrorAppDs, mkStringLit, mkConsExpr, mkNilExpr,
18
			  mkCoreTupTy, selectMatchVarL,
19
20
			  dsReboundNames, lookupReboundName )
import DsArrows		( dsProcExpr )
21
22
23
24
import DsMonad

#ifdef GHCI
	-- Template Haskell stuff iff bootstrapped
25
import DsMeta		( dsBracket )
26
27
#endif

28
29
import HsSyn
import TcHsSyn		( hsPatType )
30
31
32
33
34
35

-- NB: The desugarer, which straddles the source and Core worlds, sometimes
--     needs to see source types (newtypes etc), and sometimes not
--     So WATCH OUT; check each use of split*Ty functions.
-- Sigh.  This is a pain.

36
import TcType		( tcSplitAppTy, tcSplitFunTys, tcTyConAppArgs,
37
38
			  tcSplitTyConApp, isUnLiftedType, Type,
			  mkAppTy )
39
import Type		( splitFunTys )
40
import CoreSyn
41
import CoreUtils	( exprType, mkIfThenElse, bindNonRec )
42

43
import FieldLabel	( FieldLabel, fieldLabelTyCon )
44
import CostCentre	( mkUserCC )
45
import Id		( Id, idType, idName, recordSelectorFieldLabel )
46
import PrelInfo		( rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID )
47
import DataCon		( DataCon, dataConWrapId, dataConFieldLabels, dataConInstOrigArgTys )
48
import DataCon		( isExistentialDataCon )
49
import Name		( Name )
50
import TyCon		( tyConDataCons )
51
import TysWiredIn	( tupleCon )
52
import BasicTypes	( RecFlag(..), Boxity(..), ipNameName )
53
54
55
import PrelNames	( toPName,
			  returnMName, bindMName, thenMName, failMName,
			  mfixName )
56
import SrcLoc		( Located(..), unLoc, getLoc, noLoc )
57
import Util		( zipEqual, zipWithEqual )
58
import Bag		( bagToList )
59
import Outputable
60
import FastString
61
62
\end{code}

63
64
65
66
67
68
69

%************************************************************************
%*									*
\subsection{dsLet}
%*									*
%************************************************************************

70
@dsLet@ is a match-result transformer, taking the @MatchResult@ for the body
71
72
73
74
and transforming it into one for the let-bindings enclosing the body.

This may seem a bit odd, but (source) let bindings can contain unboxed
binds like
75
\begin{verbatim}
76
	C x# = e
77
\end{verbatim}
78
79
80
81
This must be transformed to a case expression and, if the type has
more than one constructor, may fail.

\begin{code}
82
83
dsLet :: [HsBindGroup Id] -> CoreExpr -> DsM CoreExpr
dsLet groups body = foldlDs dsBindGroup body (reverse groups)
84

85
86
dsBindGroup :: CoreExpr -> HsBindGroup Id -> DsM CoreExpr
dsBindGroup body (HsIPBinds binds)
87
88
  = foldlDs dsIPBind body binds
  where
89
90
    dsIPBind body (L _ (IPBind n e))
        = dsLExpr e	`thenDs` \ e' ->
91
92
	  returnDs (Let (NonRec (ipNameName n) e') body)

93
-- Special case for bindings which bind unlifted variables
94
95
-- We need to do a case right away, rather than building
-- a tuple and doing selections.
96
-- Silently ignore INLINE pragmas...
97
98
99
dsBindGroup body bind@(HsBindGroup hsbinds sigs is_rec)
  | [L _ (AbsBinds [] [] exports inlines binds)] <- bagToList hsbinds,
    or [isUnLiftedType (idType g) | (_, g, l) <- exports]
100
  = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
101
102
103
104
105
106
	-- Unlifted bindings are always non-recursive
	-- and are always a Fun or Pat monobind
	--
	-- ToDo: in some bizarre case it's conceivable that there
	--       could be dict binds in the 'binds'.  (See the notes
	--	 below.  Then pattern-match would fail.  Urk.)
107
108
109
110
111
112
113
114
115
116
117
118
    let
      body_w_exports		   = foldr bind_export body exports
      bind_export (tvs, g, l) body = ASSERT( null tvs )
				     bindNonRec g (Var l) body

      mk_error_app pat = mkErrorAppDs iRREFUT_PAT_ERROR_ID
				    (exprType body)
				    (showSDoc (ppr pat))
    in
    case bagToList binds of
      [L loc (FunBind (L _ fun) _ matches)]
	-> putSrcSpanDs loc				$
119
	   matchWrapper (FunRhs (idName fun)) matches 	`thenDs` \ (args, rhs) ->
120
121
122
	   ASSERT( null args )	-- Functions aren't lifted
	   returnDs (bindNonRec fun rhs body_w_exports)

123
124
      [L loc (PatBind pat grhss)]
	-> putSrcSpanDs loc			$
125
126
127
	   dsGuarded grhss 			`thenDs` \ rhs ->
	   mk_error_app pat			`thenDs` \ error_expr ->
	   matchSimply rhs PatBindRhs pat body_w_exports error_expr
128
129

      other -> pprPanic "dsLet: unlifted" (ppr bind $$ ppr body)
130
131

-- Ordinary case for bindings
132
133
dsBindGroup body (HsBindGroup binds sigs is_rec)
  = dsHsBinds NoSccs binds []  `thenDs` \ prs ->
134
135
    returnDs (Let (Rec prs) body)
	-- Use a Rec regardless of is_rec. 
136
	-- Why? Because it allows the binds to be all
137
138
139
140
141
	-- mixed up, which is what happens in one rare case
	-- Namely, for an AbsBind with no tyvars and no dicts,
	-- 	   but which does have dictionary bindings.
	-- See notes with TcSimplify.inferLoop [NO TYVARS]
	-- It turned out that wrapping a Rec here was the easiest solution
142
143
144
145
	--
	-- NB The previous case dealt with unlifted bindings, so we
	--    only have to deal with lifted ones now; so Rec is ok
\end{code}	
146
147
148

%************************************************************************
%*									*
149
\subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
150
151
152
153
%*									*
%************************************************************************

\begin{code}
154
155
156
157
dsLExpr :: LHsExpr Id -> DsM CoreExpr
dsLExpr (L loc e) = putSrcSpanDs loc $ dsExpr e

dsExpr :: HsExpr Id -> DsM CoreExpr
158

159
160
dsExpr (HsPar e) 	      = dsLExpr e
dsExpr (ExprWithTySigOut e _) = dsLExpr e
161
162
163
dsExpr (HsVar var)  = returnDs (Var var)
dsExpr (HsIPVar ip) = returnDs (Var (ipNameName ip))
dsExpr (HsLit lit)  = dsLit lit
164
-- HsOverLit has been gotten rid of by the type checker
165

166
dsExpr expr@(HsLam a_Match)
167
  = matchWrapper LambdaExpr [a_Match]	`thenDs` \ (binders, matching_code) ->
168
    returnDs (mkLams binders matching_code)
169

sof's avatar
sof committed
170
dsExpr expr@(HsApp fun arg)      
171
172
  = dsLExpr fun		`thenDs` \ core_fun ->
    dsLExpr arg		`thenDs` \ core_arg ->
173
    returnDs (core_fun `App` core_arg)
174
175
176
177
178
179
\end{code}

Operator sections.  At first it looks as if we can convert
\begin{verbatim}
	(expr op)
\end{verbatim}
180
to
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
\begin{verbatim}
	\x -> op expr x
\end{verbatim}

But no!  expr might be a redex, and we can lose laziness badly this
way.  Consider
\begin{verbatim}
	map (expr op) xs
\end{verbatim}
for example.  So we convert instead to
\begin{verbatim}
	let y = expr in \x -> op y x
\end{verbatim}
If \tr{expr} is actually just a variable, say, then the simplifier
will sort it out.

\begin{code}
sof's avatar
sof committed
198
dsExpr (OpApp e1 op _ e2)
199
  = dsLExpr op						`thenDs` \ core_op ->
sof's avatar
sof committed
200
    -- for the type of y, we need the type of op's 2nd argument
201
202
    dsLExpr e1				`thenDs` \ x_core ->
    dsLExpr e2				`thenDs` \ y_core ->
203
    returnDs (mkApps core_op [x_core, y_core])
sof's avatar
sof committed
204
    
205
dsExpr (SectionL expr op)
206
  = dsLExpr op						`thenDs` \ core_op ->
sof's avatar
sof committed
207
    -- for the type of y, we need the type of op's 2nd argument
208
    let
209
210
211
	(x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
	-- Must look through an implicit-parameter type; 
	-- newtype impossible; hence Type.splitFunTys
212
    in
213
    dsLExpr expr				`thenDs` \ x_core ->
214
    newSysLocalDs x_ty			`thenDs` \ x_id ->
sof's avatar
sof committed
215
    newSysLocalDs y_ty			`thenDs` \ y_id ->
216
217
218

    returnDs (bindNonRec x_id x_core $
	      Lam y_id (mkApps core_op [Var x_id, Var y_id]))
219

220
-- dsLExpr (SectionR op expr)	-- \ x -> op x expr
221
dsExpr (SectionR op expr)
222
  = dsLExpr op			`thenDs` \ core_op ->
sof's avatar
sof committed
223
    -- for the type of x, we need the type of op's 2nd argument
224
    let
225
226
	(x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
	-- See comment with SectionL
227
    in
228
    dsLExpr expr				`thenDs` \ y_core ->
sof's avatar
sof committed
229
    newSysLocalDs x_ty			`thenDs` \ x_id ->
230
231
232
233
    newSysLocalDs y_ty			`thenDs` \ y_id ->

    returnDs (bindNonRec y_id y_core $
	      Lam x_id (mkApps core_op [Var x_id, Var y_id]))
234

235
dsExpr (HsSCC cc expr)
236
  = dsLExpr expr			`thenDs` \ core_expr ->
237
238
    getModuleDs			`thenDs` \ mod_name ->
    returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
239

240
241
242
243

-- hdaume: core annotation

dsExpr (HsCoreAnn fs expr)
244
  = dsLExpr expr        `thenDs` \ core_expr ->
245
246
    returnDs (Note (CoreNote $ unpackFS fs) core_expr)

sof's avatar
sof committed
247
-- special case to handle unboxed tuple patterns.
248

249
dsExpr (HsCase discrim matches)
250
 | all ubx_tuple_match matches
251
 =  dsLExpr discrim			`thenDs` \ core_discrim ->
252
    matchWrapper CaseAlt matches 	`thenDs` \ ([discrim_var], matching_code) ->
253
254
255
    case matching_code of
	Case (Var x) bndr alts | x == discrim_var -> 
		returnDs (Case core_discrim bndr alts)
256
	_ -> panic ("dsLExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
257
  where
258
    ubx_tuple_match (L _ (Match [L _ (TuplePat _ Unboxed)] _ _)) = True
259
    ubx_tuple_match _ = False
260

261
262
dsExpr (HsCase discrim matches)
  = dsLExpr discrim			`thenDs` \ core_discrim ->
263
    matchWrapper CaseAlt matches	`thenDs` \ ([discrim_var], matching_code) ->
264
    returnDs (bindNonRec discrim_var core_discrim matching_code)
265

266
dsExpr (HsLet binds body)
267
  = dsLExpr body		`thenDs` \ body' ->
268
    dsLet binds body'
269

chak's avatar
chak committed
270
271
272
-- We need the `ListComp' form to use `deListComp' (rather than the "do" form)
-- because the interpretation of `stmts' depends on what sort of thing it is.
--
273
dsExpr (HsDo ListComp stmts _ result_ty)
sof's avatar
sof committed
274
  =	-- Special case for list comprehensions
275
    dsListComp stmts elt_ty
chak's avatar
chak committed
276
277
  where
    (_, [elt_ty]) = tcSplitTyConApp result_ty
278

279
dsExpr (HsDo do_or_lc stmts ids result_ty)
280
  | isDoExpr do_or_lc
281
  = dsDo do_or_lc stmts ids result_ty
chak's avatar
chak committed
282

283
dsExpr (HsDo PArrComp stmts _ result_ty)
chak's avatar
chak committed
284
  =	-- Special case for array comprehensions
285
    dsPArrComp (map unLoc stmts) elt_ty
286
  where
chak's avatar
chak committed
287
    (_, [elt_ty]) = tcSplitTyConApp result_ty
288

289
290
291
292
dsExpr (HsIf guard_expr then_expr else_expr)
  = dsLExpr guard_expr	`thenDs` \ core_guard ->
    dsLExpr then_expr	`thenDs` \ core_then ->
    dsLExpr else_expr	`thenDs` \ core_else ->
293
    returnDs (mkIfThenElse core_guard core_then core_else)
294
295
296
\end{code}


297
298
299
\noindent
\underline{\bf Type lambda and application}
%              ~~~~~~~~~~~~~~~~~~~~~~~~~~~
300
301
\begin{code}
dsExpr (TyLam tyvars expr)
302
  = dsLExpr expr `thenDs` \ core_expr ->
303
    returnDs (mkLams tyvars core_expr)
304

sof's avatar
sof committed
305
dsExpr (TyApp expr tys)
306
  = dsLExpr expr		`thenDs` \ core_expr ->
307
    returnDs (mkTyApps core_expr tys)
308
309
310
\end{code}


311
312
313
\noindent
\underline{\bf Various data construction things}
%              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
314
\begin{code}
315
dsExpr (ExplicitList ty xs)
sof's avatar
sof committed
316
317
  = go xs
  where
318
    go []     = returnDs (mkNilExpr ty)
319
    go (x:xs) = dsLExpr x				`thenDs` \ core_x ->
sof's avatar
sof committed
320
		go xs					`thenDs` \ core_xs ->
321
		returnDs (mkConsExpr ty core_x core_xs)
322

chak's avatar
chak committed
323
324
325
326
327
328
329
330
331
332
333
-- we create a list from the array elements and convert them into a list using
-- `PrelPArr.toP'
--
-- * the main disadvantage to this scheme is that `toP' traverses the list
--   twice: once to determine the length and a second time to put to elements
--   into the array; this inefficiency could be avoided by exposing some of
--   the innards of `PrelPArr' to the compiler (ie, have a `PrelPArrBase') so
--   that we can exploit the fact that we already know the length of the array
--   here at compile time
--
dsExpr (ExplicitPArr ty xs)
334
  = dsLookupGlobalId toPName				`thenDs` \toP      ->
chak's avatar
chak committed
335
336
337
    dsExpr (ExplicitList ty xs)				`thenDs` \coreList ->
    returnDs (mkApps (Var toP) [Type ty, coreList])

338
dsExpr (ExplicitTuple expr_list boxity)
339
  = mappM dsLExpr expr_list	  `thenDs` \ core_exprs  ->
340
    returnDs (mkConApp (tupleCon boxity (length expr_list))
341
	    	       (map (Type .  exprType) core_exprs ++ core_exprs))
342
343

dsExpr (ArithSeqOut expr (From from))
344
345
  = dsLExpr expr		  `thenDs` \ expr2 ->
    dsLExpr from		  `thenDs` \ from2 ->
346
    returnDs (App expr2 from2)
347
348

dsExpr (ArithSeqOut expr (FromTo from two))
349
350
351
  = dsLExpr expr		  `thenDs` \ expr2 ->
    dsLExpr from		  `thenDs` \ from2 ->
    dsLExpr two		  `thenDs` \ two2 ->
352
    returnDs (mkApps expr2 [from2, two2])
353
354

dsExpr (ArithSeqOut expr (FromThen from thn))
355
356
357
  = dsLExpr expr		  `thenDs` \ expr2 ->
    dsLExpr from		  `thenDs` \ from2 ->
    dsLExpr thn		  `thenDs` \ thn2 ->
358
    returnDs (mkApps expr2 [from2, thn2])
359
360

dsExpr (ArithSeqOut expr (FromThenTo from thn two))
361
362
363
364
  = dsLExpr expr		  `thenDs` \ expr2 ->
    dsLExpr from		  `thenDs` \ from2 ->
    dsLExpr thn		  `thenDs` \ thn2 ->
    dsLExpr two		  `thenDs` \ two2 ->
365
    returnDs (mkApps expr2 [from2, thn2, two2])
chak's avatar
chak committed
366
367

dsExpr (PArrSeqOut expr (FromTo from two))
368
369
370
  = dsLExpr expr		  `thenDs` \ expr2 ->
    dsLExpr from		  `thenDs` \ from2 ->
    dsLExpr two		  `thenDs` \ two2 ->
chak's avatar
chak committed
371
372
373
    returnDs (mkApps expr2 [from2, two2])

dsExpr (PArrSeqOut expr (FromThenTo from thn two))
374
375
376
377
  = dsLExpr expr		  `thenDs` \ expr2 ->
    dsLExpr from		  `thenDs` \ from2 ->
    dsLExpr thn		  `thenDs` \ thn2 ->
    dsLExpr two		  `thenDs` \ two2 ->
chak's avatar
chak committed
378
379
380
381
382
383
    returnDs (mkApps expr2 [from2, thn2, two2])

dsExpr (PArrSeqOut expr _)
  = panic "DsExpr.dsExpr: Infinite parallel array!"
    -- the parser shouldn't have generated it and the renamer and typechecker
    -- shouldn't have let it through
384
385
\end{code}

386
387
388
\noindent
\underline{\bf Record construction and update}
%              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
389
For record construction we do this (assuming T has three arguments)
390
\begin{verbatim}
391
392
393
394
395
396
	T { op2 = e }
==>
	let err = /\a -> recConErr a 
	T (recConErr t1 "M.lhs/230/op1") 
	  e 
	  (recConErr t1 "M.lhs/230/op3")
397
398
\end{verbatim}
@recConErr@ then converts its arugment string into a proper message
399
before printing it as
400
401
402
\begin{verbatim}
	M.lhs, line 230: missing field op1 was evaluated
\end{verbatim}
403

404
405
We also handle @C{}@ as valid construction syntax for an unlabelled
constructor @C@, setting all of @C@'s fields to bottom.
406

407
\begin{code}
408
dsExpr (RecordConOut data_con con_expr rbinds)
409
  = dsLExpr con_expr	`thenDs` \ con_expr' ->
410
    let
411
	(arg_tys, _) = tcSplitFunTys (exprType con_expr')
412
413
	-- A newtype in the corner should be opaque; 
	-- hence TcType.tcSplitFunTys
414

415
	mk_arg (arg_ty, lbl)
416
	  = case [rhs | (L _ sel_id, rhs) <- rbinds,
417
418
			lbl == recordSelectorFieldLabel sel_id] of
	      (rhs:rhss) -> ASSERT( null rhss )
419
		 	    dsLExpr rhs
420
	      []         -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
421
422
423
	unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""

	labels = dataConFieldLabels data_con
424
    in
425
426

    (if null labels
427
428
	then mappM unlabelled_bottom arg_tys
	else mappM mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
429
430
	`thenDs` \ con_args ->

431
    returnDs (mkApps con_expr' con_args)
432
433
434
\end{code}

Record update is a little harder. Suppose we have the decl:
435
\begin{verbatim}
436
	data T = T1 {op1, op2, op3 :: Int}
437
	       | T2 {op4, op2 :: Int}
438
	       | T3
439
\end{verbatim}
440
Then we translate as follows:
441
\begin{verbatim}
442
443
444
445
446
447
448
	r { op2 = e }
===>
	let op2 = e in
	case r of
	  T1 op1 _ op3 -> T1 op1 op2 op3
	  T2 op4 _     -> T2 op4 op2
	  other	       -> recUpdError "M.lhs/230"
449
450
\end{verbatim}
It's important that we use the constructor Ids for @T1@, @T2@ etc on the
451
RHSs, and do not generate a Core constructor application directly, because the constructor
452
453
454
455
might do some argument-evaluation first; and may have to throw away some
dictionaries.

\begin{code}
456
dsExpr (RecordUpdOut record_expr record_in_ty record_out_ty [])
457
  = dsLExpr record_expr
458

459
dsExpr expr@(RecordUpdOut record_expr record_in_ty record_out_ty rbinds)
460
  = dsLExpr record_expr	 	`thenDs` \ record_expr' ->
461
462
463

	-- Desugar the rbinds, and generate let-bindings if
	-- necessary so that we don't lose sharing
464
465

    let
466
467
	in_inst_tys  = tcTyConAppArgs record_in_ty	-- Newtype opaque
	out_inst_tys = tcTyConAppArgs record_out_ty	-- Newtype opaque
468

469
	mk_val_arg field old_arg_id 
470
	  = case [rhs | (L _ sel_id, rhs) <- rbinds, 
471
			field == recordSelectorFieldLabel sel_id] of
472
	      (rhs:rest) -> ASSERT(null rest) rhs
473
	      []	 -> nlHsVar old_arg_id
474
475

	mk_alt con
476
	  = newSysLocalsDs (dataConInstOrigArgTys con in_inst_tys) `thenDs` \ arg_ids ->
477
		-- This call to dataConArgTys won't work for existentials
478
	    let 
479
480
		val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
					(dataConFieldLabels con) arg_ids
481
482
483
484
		rhs = foldl (\a b -> nlHsApp a b)
			(noLoc $ TyApp (nlHsVar (dataConWrapId con)) 
				out_inst_tys)
			  val_args
485
	    in
486
	    returnDs (mkSimpleMatch [noLoc $ ConPatOut con (PrefixCon (map nlVarPat arg_ids)) record_in_ty [] []]
487
				    rhs
488
				    record_out_ty)
489
    in
490
	-- Record stuff doesn't work for existentials
491
492
493
	-- The type checker checks for this, but we need 
	-- worry only about the constructors that are to be updated
    ASSERT2( all (not . isExistentialDataCon) cons_to_upd, ppr expr )
494

495
496
497
498
	-- It's important to generate the match with matchWrapper,
	-- and the right hand sides with applications of the wrapper Id
	-- so that everything works when we are doing fancy unboxing on the
	-- constructor aguments.
499
    mappM mk_alt cons_to_upd		`thenDs` \ alts ->
500
    matchWrapper RecUpd alts		`thenDs` \ ([discrim_var], matching_code) ->
501
502

    returnDs (bindNonRec discrim_var record_expr' matching_code)
503
504

  where
505
    updated_fields :: [FieldLabel]
506
507
    updated_fields = [ recordSelectorFieldLabel sel_id 
		     | (L _ sel_id,_) <- rbinds]
508
509
510
511
512
513
514
515
516

	-- Get the type constructor from the first field label, 
	-- so that we are sure it'll have all its DataCons
	-- (In GHCI, it's possible that some TyCons may not have all
	--  their constructors, in a module-loop situation.)
    tycon       = fieldLabelTyCon (head updated_fields)
    data_cons   = tyConDataCons tycon
    cons_to_upd = filter has_all_fields data_cons

517
    has_all_fields :: DataCon -> Bool
518
    has_all_fields con_id 
519
      = all (`elem` con_fields) updated_fields
520
      where
521
	con_fields = dataConFieldLabels con_id
522
523
\end{code}

524
525
526
527

\noindent
\underline{\bf Dictionary lambda and application}
%              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
528
529
530
531
532
@DictLam@ and @DictApp@ turn into the regular old things.
(OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
complicated; reminiscent of fully-applied constructors.
\begin{code}
dsExpr (DictLam dictvars expr)
533
  = dsLExpr expr `thenDs` \ core_expr ->
534
    returnDs (mkLams dictvars core_expr)
535
536
537

------------------

sof's avatar
sof committed
538
dsExpr (DictApp expr dicts)	-- becomes a curried application
539
  = dsLExpr expr			`thenDs` \ core_expr ->
540
    returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
541
542
\end{code}

543
544
545
546
547
548
549
Here is where we desugar the Template Haskell brackets and escapes

\begin{code}
-- Template Haskell stuff

#ifdef GHCI	/* Only if bootstrapping */
dsExpr (HsBracketOut x ps) = dsBracket x ps
550
dsExpr (HsSpliceE s)       = pprPanic "dsExpr:splice" (ppr s)
551
552
#endif

553
-- Arrow notation extension
554
dsExpr (HsProc pat cmd) = dsProcExpr pat cmd
555
556
557
\end{code}


558
559
\begin{code}

560
561
562
563
#ifdef DEBUG
-- HsSyn constructs that just shouldn't be here:
dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
dsExpr (ArithSeqIn _)	    = panic "dsExpr:ArithSeqIn"
chak's avatar
chak committed
564
dsExpr (PArrSeqIn _)	    = panic "dsExpr:PArrSeqIn"
565
566
#endif

567
568
\end{code}

sof's avatar
sof committed
569
%--------------------------------------------------------------------
570

571
572
573
Desugar 'do' and 'mdo' expressions (NOT list comprehensions, they're
handled in DsListComp).  Basically does the translation given in the
Haskell 98 report:
574

575
\begin{code}
576
dsDo	:: HsStmtContext Name
577
	-> [LStmt Id]
578
579
	-> ReboundNames Id	-- id for: [return,fail,>>=,>>] and possibly mfixName
	-> Type			-- Element type; the whole expression has type (m t)
580
581
	-> DsM CoreExpr

582
dsDo do_or_lc stmts ids result_ty
583
584
585
586
587
588
  = dsReboundNames ids		`thenDs` \ (meth_binds, ds_meths) ->
    let
	fail_id   = lookupReboundName ds_meths failMName
	bind_id   = lookupReboundName ds_meths bindMName
	then_id   = lookupReboundName ds_meths thenMName

589
	(m_ty, b_ty) = tcSplitAppTy result_ty	-- result_ty must be of the form (m b)
590
	
rrt's avatar
rrt committed
591
	-- For ExprStmt, see the comments near HsExpr.Stmt about 
592
593
	-- exactly what ExprStmts mean!
	--
594
	-- In dsDo we can only see DoStmt and ListComp (no guards)
595

596
	go [ResultStmt expr]     = dsLExpr expr
597

598
599
600

	go (ExprStmt expr a_ty : stmts)
	  = dsLExpr expr		`thenDs` \ expr2 ->
601
	    go stmts     		`thenDs` \ rest  ->
602
	    returnDs (mkApps then_id [Type a_ty, Type b_ty, expr2, rest])
603
    
604
	go (LetStmt binds : stmts)
605
606
607
	  = go stmts 		`thenDs` \ rest   ->
	    dsLet binds	rest
	    
608
	go (BindStmt pat expr : stmts)
609
	  = go stmts			`thenDs` \ body -> 
610
611
	    dsLExpr expr 	 	`thenDs` \ rhs ->
	    mkStringLit (mk_msg (getLoc pat))	`thenDs` \ core_msg ->
612
	    let
613
614
		-- In a do expression, pattern-match failure just calls
		-- the monadic 'fail' rather than throwing an exception
615
		fail_expr  = mkApps fail_id [Type b_ty, core_msg]
616
		a_ty       = hsPatType pat
617
	    in
618
	    selectMatchVarL pat		 	 		`thenDs` \ var ->
619
620
    	    matchSimply (Var var) (StmtCtxt do_or_lc) pat
			body fail_expr				`thenDs` \ match_code ->
621
	    returnDs (mkApps bind_id [Type a_ty, Type b_ty, rhs, Lam var match_code])
622

623
	go (RecStmt rec_stmts later_vars rec_vars rec_rets : stmts)
624
625
	  = go (bind_stmt : stmts)
	  where
626
	    bind_stmt = dsRecStmt m_ty ds_meths rec_stmts later_vars rec_vars rec_rets
627
	    
628
    in
629
    go (map unLoc stmts)			`thenDs` \ stmts_code ->
630
    returnDs (foldr Let stmts_code meth_binds)
631

632
  where
633
    mk_msg locn = "Pattern match failure in do expression at " ++ showSDoc (ppr locn)
634
\end{code}
635
636
637
638
639
640
641
642
643
644

Translation for RecStmt's: 
-----------------------------
We turn (RecStmt [v1,..vn] stmts) into:
  
  (v1,..,vn) <- mfix (\~(v1,..vn). do stmts
				      return (v1,..vn))

\begin{code}
dsRecStmt :: Type		-- Monad type constructor :: * -> *
645
	  -> [(Name,Id)]	-- Rebound Ids
646
647
648
	  -> [LStmt Id]
  	  -> [Id] -> [Id] -> [LHsExpr Id]
	  -> Stmt Id
649
dsRecStmt m_ty ds_meths stmts later_vars rec_vars rec_rets
650
  = ASSERT( length vars == length rets )
651
    BindStmt tup_pat mfix_app
652
  where 
653
	vars@(var1:rest) = later_vars           ++ rec_vars		-- Always at least one
654
	rets@(ret1:_)    = map nlHsVar later_vars ++ rec_rets
655
	one_var          = null rest
656

657
658
	mfix_app = nlHsApp (noLoc $ TyApp (nlHsVar mfix_id) [tup_ty]) mfix_arg
	mfix_arg = noLoc $ HsLam (mkSimpleMatch [tup_pat] body tup_ty)
659

660
	tup_expr | one_var   = ret1
661
		 | otherwise = noLoc $ ExplicitTuple rets Boxed
662
663
	tup_ty   	     = mkCoreTupTy (map idType vars)
					-- Deals with singleton case
664
665
	tup_pat  | one_var   = nlVarPat var1
		 | otherwise = noLoc $ LazyPat (noLoc $ TuplePat (map nlVarPat vars) Boxed)
666

667
	body = noLoc $ HsDo DoExpr (stmts ++ [return_stmt]) 
668
			   [(n, HsVar id) | (n,id) <- ds_meths]	-- A bit of a hack
669
670
			   (mkAppTy m_ty tup_ty)

671
672
673
  	Var return_id = lookupReboundName ds_meths returnMName
	Var mfix_id   = lookupReboundName ds_meths mfixName

674
675
	return_stmt = noLoc $ ResultStmt return_app
	return_app  = nlHsApp (noLoc $ TyApp (nlHsVar return_id) [tup_ty]) tup_expr
676
\end{code}