[project @ 1996-12-19 09:10:02 by simonpj]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsExpr.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[DsExpr]{Matching expressions (Exprs)}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module DsExpr ( dsExpr ) where
10
11 IMP_Ubiq()
12 IMPORT_DELOOPER(DsLoop)         -- partly to get dsBinds, partly to chk dsExpr
13
14 import HsSyn            ( failureFreePat,
15                           HsExpr(..), OutPat(..), HsLit(..), ArithSeqInfo(..),
16                           Stmt(..), Match(..), Qualifier, HsBinds, HsType,
17                           GRHSsAndBinds
18                         )
19 import TcHsSyn          ( SYN_IE(TypecheckedHsExpr), SYN_IE(TypecheckedHsBinds),
20                           SYN_IE(TypecheckedRecordBinds), SYN_IE(TypecheckedPat),
21                           SYN_IE(TypecheckedStmt)
22                         )
23 import CoreSyn
24
25 import DsMonad
26 import DsCCall          ( dsCCall )
27 import DsHsSyn          ( outPatType )
28 import DsListComp       ( dsListComp )
29 import DsUtils          ( mkAppDs, mkConDs, mkPrimDs, dsExprToAtom,
30                           mkErrorAppDs, showForErr, EquationInfo,
31                           MatchResult, SYN_IE(DsCoreArg)
32                         )
33 import Match            ( matchWrapper )
34
35 import CoreUtils        ( coreExprType, substCoreExpr, argToExpr,
36                           mkCoreIfThenElse, unTagBinders )
37 import CostCentre       ( mkUserCC )
38 import FieldLabel       ( fieldLabelType, FieldLabel )
39 import Id               ( idType, nullIdEnv, addOneToIdEnv,
40                           dataConArgTys, dataConFieldLabels,
41                           recordSelectorFieldLabel
42                         )
43 import Literal          ( mkMachInt, Literal(..) )
44 import Name             ( Name{--O only-} )
45 import PprStyle         ( PprStyle(..) )
46 import PprType          ( GenType )
47 import PrelVals         ( rEC_CON_ERROR_ID, rEC_UPD_ERROR_ID, voidId )
48 import Pretty           ( ppShow, ppBesides, ppPStr, ppStr )
49 import TyCon            ( isDataTyCon, isNewTyCon )
50 import Type             ( splitSigmaTy, splitFunTy, typePrimRep,
51                           getAppDataTyConExpandingDicts, getAppTyCon, applyTy,
52                           maybeBoxedPrimType
53                         )
54 import TysPrim          ( voidTy )
55 import TysWiredIn       ( mkTupleTy, tupleCon, nilDataCon, consDataCon,
56                           charDataCon, charTy
57                         )
58 import TyVar            ( nullTyVarEnv, addOneToTyVarEnv, GenTyVar{-instance Eq-} )
59 import Usage            ( SYN_IE(UVar) )
60 import Util             ( zipEqual, pprError, panic, assertPanic )
61
62 mk_nil_con ty = mkCon nilDataCon [] [ty] []  -- micro utility...
63 \end{code}
64
65 The funny business to do with variables is that we look them up in the
66 Id-to-Id and Id-to-Id maps that the monadery is carrying
67 around; if we get hits, we use the value accordingly.
68
69 %************************************************************************
70 %*                                                                      *
71 \subsection[DsExpr-vars-and-cons]{Variables and constructors}
72 %*                                                                      *
73 %************************************************************************
74
75 \begin{code}
76 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
77
78 dsExpr e@(HsVar var) = dsApp e []
79 \end{code}
80
81 %************************************************************************
82 %*                                                                      *
83 \subsection[DsExpr-literals]{Literals}
84 %*                                                                      *
85 %************************************************************************
86
87 We give int/float literals type Integer and Rational, respectively.
88 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
89 around them.
90
91 ToDo: put in range checks for when converting "i"
92 (or should that be in the typechecker?)
93
94 For numeric literals, we try to detect there use at a standard type
95 (Int, Float, etc.) are directly put in the right constructor.
96 [NB: down with the @App@ conversion.]
97 Otherwise, we punt, putting in a "NoRep" Core literal (where the
98 representation decisions are delayed)...
99
100 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
101
102 \begin{code}
103 dsExpr (HsLitOut (HsString s) _)
104   | _NULL_ s
105   = returnDs (mk_nil_con charTy)
106
107   | _LENGTH_ s == 1
108   = let
109         the_char = mkCon charDataCon [] [] [LitArg (MachChar (_HEAD_ s))]
110         the_nil  = mk_nil_con charTy
111     in
112     mkConDs consDataCon [TyArg charTy, VarArg the_char, VarArg the_nil]
113
114 -- "_" => build (\ c n -> c 'c' n)      -- LATER
115
116 -- "str" ==> build (\ c n -> foldr charTy T c n "str")
117
118 {- LATER:
119 dsExpr (HsLitOut (HsString str) _)
120   = newTyVarsDs [alphaTyVar]            `thenDs` \ [new_tyvar] ->
121     let
122         new_ty = mkTyVarTy new_tyvar
123     in
124     newSysLocalsDs [
125                 charTy `mkFunTy` (new_ty `mkFunTy` new_ty),
126                 new_ty,
127                        mkForallTy [alphaTyVar]
128                                ((charTy `mkFunTy` (alphaTy `mkFunTy` alphaTy))
129                                         `mkFunTy` (alphaTy `mkFunTy` alphaTy))
130                 ]                       `thenDs` \ [c,n,g] ->
131      returnDs (mkBuild charTy new_tyvar c n g (
132         foldl App
133           (CoTyApp (CoTyApp (Var foldrId) charTy) new_ty) *** ensure non-prim type ***
134           [VarArg c,VarArg n,LitArg (NoRepStr str)]))
135 -}
136
137 -- otherwise, leave it as a NoRepStr;
138 -- the Core-to-STG pass will wrap it in an application of "unpackCStringId".
139
140 dsExpr (HsLitOut (HsString str) _)
141   = returnDs (Lit (NoRepStr str))
142
143 dsExpr (HsLitOut (HsLitLit s) ty)
144   = returnDs ( mkCon data_con [] [] [LitArg (MachLitLit s kind)] )
145   where
146     (data_con, kind)
147       = case (maybeBoxedPrimType ty) of
148           Just (boxing_data_con, prim_ty)
149             -> (boxing_data_con, typePrimRep prim_ty)
150           Nothing
151             -> pprError "ERROR: ``literal-literal'' not a single-constructor type: "
152                         (ppBesides [ppPStr s, ppStr "; type: ", ppr PprDebug ty])
153
154 dsExpr (HsLitOut (HsInt i) ty)
155   = returnDs (Lit (NoRepInteger i ty))
156
157 dsExpr (HsLitOut (HsFrac r) ty)
158   = returnDs (Lit (NoRepRational r ty))
159
160 -- others where we know what to do:
161
162 dsExpr (HsLitOut (HsIntPrim i) _)
163   = if (i >= toInteger minInt && i <= toInteger maxInt) then
164         returnDs (Lit (mkMachInt i))
165     else
166         error ("ERROR: Int constant " ++ show i ++ out_of_range_msg)
167
168 dsExpr (HsLitOut (HsFloatPrim f) _)
169   = returnDs (Lit (MachFloat f))
170     -- ToDo: range checking needed!
171
172 dsExpr (HsLitOut (HsDoublePrim d) _)
173   = returnDs (Lit (MachDouble d))
174     -- ToDo: range checking needed!
175
176 dsExpr (HsLitOut (HsChar c) _)
177   = returnDs ( mkCon charDataCon [] [] [LitArg (MachChar c)] )
178
179 dsExpr (HsLitOut (HsCharPrim c) _)
180   = returnDs (Lit (MachChar c))
181
182 dsExpr (HsLitOut (HsStringPrim s) _)
183   = returnDs (Lit (MachStr s))
184
185 -- end of literals magic. --
186
187 dsExpr expr@(HsLam a_Match)
188   = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
189     returnDs ( mkValLam binders matching_code )
190
191 dsExpr expr@(HsApp e1 e2)    = dsApp expr []
192 dsExpr expr@(OpApp e1 op e2) = dsApp expr []
193 \end{code}
194
195 Operator sections.  At first it looks as if we can convert
196 \begin{verbatim}
197         (expr op)
198 \end{verbatim}
199 to
200 \begin{verbatim}
201         \x -> op expr x
202 \end{verbatim}
203
204 But no!  expr might be a redex, and we can lose laziness badly this
205 way.  Consider
206 \begin{verbatim}
207         map (expr op) xs
208 \end{verbatim}
209 for example.  So we convert instead to
210 \begin{verbatim}
211         let y = expr in \x -> op y x
212 \end{verbatim}
213 If \tr{expr} is actually just a variable, say, then the simplifier
214 will sort it out.
215
216 \begin{code}
217 dsExpr (SectionL expr op)
218   = dsExpr op                   `thenDs` \ core_op ->
219     dsExpr expr                 `thenDs` \ core_expr ->
220     dsExprToAtom (VarArg core_expr)     $ \ y_atom ->
221
222     -- for the type of x, we need the type of op's 2nd argument
223     let
224         x_ty  = case (splitSigmaTy (coreExprType core_op)) of { (_, _, tau_ty) ->
225                 case (splitFunTy tau_ty)                   of {
226                   ((_:arg2_ty:_), _) -> arg2_ty;
227                   _ -> panic "dsExpr:SectionL:arg 2 ty" }}
228     in
229     newSysLocalDs x_ty          `thenDs` \ x_id ->
230     returnDs (mkValLam [x_id] (core_op `App` y_atom `App` VarArg x_id)) 
231
232 -- dsExpr (SectionR op expr)    -- \ x -> op x expr
233 dsExpr (SectionR op expr)
234   = dsExpr op                   `thenDs` \ core_op ->
235     dsExpr expr                 `thenDs` \ core_expr ->
236     dsExprToAtom (VarArg core_expr)     $ \ y_atom ->
237
238     -- for the type of x, we need the type of op's 1st argument
239     let
240         x_ty  = case (splitSigmaTy (coreExprType core_op)) of { (_, _, tau_ty) ->
241                 case (splitFunTy tau_ty)                   of {
242                   ((arg1_ty:_), _) -> arg1_ty;
243                   _ -> panic "dsExpr:SectionR:arg 1 ty" }}
244     in
245     newSysLocalDs x_ty          `thenDs` \ x_id ->
246     returnDs (mkValLam [x_id] (core_op `App` VarArg x_id `App` y_atom))
247
248 dsExpr (CCall label args may_gc is_asm result_ty)
249   = mapDs dsExpr args           `thenDs` \ core_args ->
250     dsCCall label core_args may_gc is_asm result_ty
251         -- dsCCall does all the unboxification, etc.
252
253 dsExpr (HsSCC cc expr)
254   = dsExpr expr                 `thenDs` \ core_expr ->
255     getModuleAndGroupDs         `thenDs` \ (mod_name, group_name) ->
256     returnDs ( SCC (mkUserCC cc mod_name group_name) core_expr)
257
258 dsExpr expr@(HsCase discrim matches src_loc)
259   = putSrcLocDs src_loc $
260     dsExpr discrim                              `thenDs` \ core_discrim ->
261     matchWrapper CaseMatch matches "case"       `thenDs` \ ([discrim_var], matching_code) ->
262     returnDs ( mkCoLetAny (NonRec discrim_var core_discrim) matching_code )
263
264 dsExpr (ListComp expr quals)
265   = dsExpr expr `thenDs` \ core_expr ->
266     dsListComp core_expr quals
267
268 dsExpr (HsLet binds expr)
269   = dsBinds False binds `thenDs` \ core_binds ->
270     dsExpr expr         `thenDs` \ core_expr ->
271     returnDs ( mkCoLetsAny core_binds core_expr )
272
273 dsExpr (HsDoOut stmts then_id zero_id src_loc)
274   = putSrcLocDs src_loc $
275     dsDo then_id zero_id stmts
276
277 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
278   = putSrcLocDs src_loc $
279     dsExpr guard_expr   `thenDs` \ core_guard ->
280     dsExpr then_expr    `thenDs` \ core_then ->
281     dsExpr else_expr    `thenDs` \ core_else ->
282     returnDs (mkCoreIfThenElse core_guard core_then core_else)
283 \end{code}
284
285
286 Type lambda and application
287 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
288 \begin{code}
289 dsExpr (TyLam tyvars expr)
290   = dsExpr expr `thenDs` \ core_expr ->
291     returnDs (mkTyLam tyvars core_expr)
292
293 dsExpr expr@(TyApp e tys) = dsApp expr []
294 \end{code}
295
296
297 Various data construction things
298 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
299 \begin{code}
300 dsExpr (ExplicitListOut ty xs)
301   = case xs of
302       []     -> returnDs (mk_nil_con ty)
303       (y:ys) ->
304         dsExpr y                            `thenDs` \ core_hd  ->
305         dsExpr (ExplicitListOut ty ys)  `thenDs` \ core_tl  ->
306         mkConDs consDataCon [TyArg ty, VarArg core_hd, VarArg core_tl]
307
308 dsExpr (ExplicitTuple expr_list)
309   = mapDs dsExpr expr_list        `thenDs` \ core_exprs  ->
310     mkConDs (tupleCon (length expr_list))
311             (map (TyArg . coreExprType) core_exprs ++ map VarArg core_exprs)
312
313 -- Two cases, one for ordinary constructors and one for newtype constructors
314 dsExpr (HsCon con tys args)
315   | isDataTyCon tycon                   -- The usual datatype case
316   = mapDs dsExpr args   `thenDs` \ args_exprs ->
317     mkConDs con (map TyArg tys ++ map VarArg args_exprs)
318
319   | otherwise                           -- The newtype case
320   = ASSERT( isNewTyCon tycon )
321     ASSERT( null rest_args )
322     dsExpr first_arg            `thenDs` \ arg_expr ->
323     returnDs (Coerce (CoerceIn con) result_ty arg_expr)
324
325   where
326     (first_arg:rest_args) = args
327     (args_tys, result_ty) = splitFunTy (foldl applyTy (idType con) tys)
328     (tycon,_)             = getAppTyCon result_ty
329
330 dsExpr (ArithSeqOut expr (From from))
331   = dsExpr expr           `thenDs` \ expr2 ->
332     dsExpr from           `thenDs` \ from2 ->
333     mkAppDs expr2 [VarArg from2]
334
335 dsExpr (ArithSeqOut expr (FromTo from two))
336   = dsExpr expr           `thenDs` \ expr2 ->
337     dsExpr from           `thenDs` \ from2 ->
338     dsExpr two            `thenDs` \ two2 ->
339     mkAppDs expr2 [VarArg from2, VarArg two2]
340
341 dsExpr (ArithSeqOut expr (FromThen from thn))
342   = dsExpr expr           `thenDs` \ expr2 ->
343     dsExpr from           `thenDs` \ from2 ->
344     dsExpr thn            `thenDs` \ thn2 ->
345     mkAppDs expr2 [VarArg from2, VarArg thn2]
346
347 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
348   = dsExpr expr           `thenDs` \ expr2 ->
349     dsExpr from           `thenDs` \ from2 ->
350     dsExpr thn            `thenDs` \ thn2 ->
351     dsExpr two            `thenDs` \ two2 ->
352     mkAppDs expr2 [VarArg from2, VarArg thn2, VarArg two2]
353 \end{code}
354
355 Record construction and update
356 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
357 For record construction we do this (assuming T has three arguments)
358
359         T { op2 = e }
360 ==>
361         let err = /\a -> recConErr a 
362         T (recConErr t1 "M.lhs/230/op1") 
363           e 
364           (recConErr t1 "M.lhs/230/op3")
365
366 recConErr then converts its arugment string into a proper message
367 before printing it as
368
369         M.lhs, line 230: missing field op1 was evaluated
370
371
372 \begin{code}
373 dsExpr (RecordCon con_expr rbinds)
374   = dsExpr con_expr     `thenDs` \ con_expr' ->
375     let
376         con_id       = get_con con_expr'
377         (arg_tys, _) = splitFunTy (coreExprType con_expr')
378
379         mk_arg (arg_ty, lbl)
380           = case [rhs | (sel_id,rhs,_) <- rbinds,
381                         lbl == recordSelectorFieldLabel sel_id] of
382               (rhs:rhss) -> ASSERT( null rhss )
383                             dsExpr rhs
384               []         -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showForErr lbl)
385     in
386     mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys (dataConFieldLabels con_id)) `thenDs` \ con_args ->
387     mkAppDs con_expr' (map VarArg con_args)
388   where
389         -- "con_expr'" is simply an application of the constructor Id
390         -- to types and (perhaps) dictionaries. This gets the constructor...
391     get_con (Var con)   = con
392     get_con (App fun _) = get_con fun
393 \end{code}
394
395 Record update is a little harder. Suppose we have the decl:
396
397         data T = T1 {op1, op2, op3 :: Int}
398                | T2 {op4, op2 :: Int}
399                | T3
400
401 Then we translate as follows:
402
403         r { op2 = e }
404 ===>
405         let op2 = e in
406         case r of
407           T1 op1 _ op3 -> T1 op1 op2 op3
408           T2 op4 _     -> T2 op4 op2
409           other        -> recUpdError "M.lhs/230"
410
411 It's important that we use the constructor Ids for T1, T2 etc on the
412 RHSs, and do not generate a Core Con directly, because the constructor
413 might do some argument-evaluation first; and may have to throw away some
414 dictionaries.
415
416 \begin{code}
417 dsExpr (RecordUpdOut record_expr dicts rbinds)
418   = dsExpr record_expr   `thenDs` \ record_expr' ->
419
420         -- Desugar the rbinds, and generate let-bindings if
421         -- necessary so that we don't lose sharing
422     dsRbinds rbinds             $ \ rbinds' ->
423     let
424         record_ty               = coreExprType record_expr'
425         (tycon, inst_tys, cons) = --trace "DsExpr.getAppDataTyConExpandingDicts" $
426                                   getAppDataTyConExpandingDicts record_ty
427         cons_to_upd             = filter has_all_fields cons
428
429         -- initial_args are passed to every constructor
430         initial_args            = map TyArg inst_tys ++ map VarArg dicts
431                 
432         mk_val_arg (field, arg_id) 
433           = case [arg | (f, arg) <- rbinds',
434                         field == recordSelectorFieldLabel f] of
435               (arg:args) -> ASSERT(null args)
436                             arg
437               []         -> VarArg arg_id
438
439         mk_alt con
440           = newSysLocalsDs (dataConArgTys con inst_tys) `thenDs` \ arg_ids ->
441             let 
442                 val_args = map mk_val_arg (zipEqual "dsExpr:RecordUpd" (dataConFieldLabels con) arg_ids)
443             in
444             returnDs (con, arg_ids, mkGenApp (mkGenApp (Var con) initial_args) val_args)
445
446         mk_default
447           | length cons_to_upd == length cons 
448           = returnDs NoDefault
449           | otherwise                       
450           = newSysLocalDs record_ty                     `thenDs` \ deflt_id ->
451             mkErrorAppDs rEC_UPD_ERROR_ID record_ty ""  `thenDs` \ err ->
452             returnDs (BindDefault deflt_id err)
453     in
454     mapDs mk_alt cons_to_upd    `thenDs` \ alts ->
455     mk_default                  `thenDs` \ deflt ->
456
457     returnDs (Case record_expr' (AlgAlts alts deflt))
458
459   where
460     has_all_fields :: Id -> Bool
461     has_all_fields con_id 
462       = all ok rbinds
463       where
464         con_fields        = dataConFieldLabels con_id
465         ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
466 \end{code}
467
468 Dictionary lambda and application
469 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
470 @DictLam@ and @DictApp@ turn into the regular old things.
471 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
472 complicated; reminiscent of fully-applied constructors.
473 \begin{code}
474 dsExpr (DictLam dictvars expr)
475   = dsExpr expr `thenDs` \ core_expr ->
476     returnDs( mkValLam dictvars core_expr )
477
478 ------------------
479
480 dsExpr expr@(DictApp e dicts)   -- becomes a curried application
481   = dsApp expr []
482 \end{code}
483
484 @SingleDicts@ become @Locals@; @Dicts@ turn into tuples, unless
485 of length 0 or 1.
486 @ClassDictLam dictvars methods expr@ is ``the opposite'':
487 \begin{verbatim}
488 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
489 \end{verbatim}
490 \begin{code}
491 dsExpr (SingleDict dict)        -- just a local
492   = lookupEnvWithDefaultDs dict (Var dict)
493
494 dsExpr (Dictionary dicts methods)
495   = -- hey, these things may have been substituted away...
496     zipWithDs lookupEnvWithDefaultDs
497               dicts_and_methods dicts_and_methods_exprs
498                         `thenDs` \ core_d_and_ms ->
499
500     (case num_of_d_and_ms of
501       0 -> returnDs (Var voidId)
502
503       1 -> returnDs (head core_d_and_ms) -- just a single Id
504
505       _ ->          -- tuple 'em up
506            mkConDs (tupleCon num_of_d_and_ms)
507                    (map (TyArg . coreExprType) core_d_and_ms ++ map VarArg core_d_and_ms)
508     )
509   where
510     dicts_and_methods       = dicts ++ methods
511     dicts_and_methods_exprs = map Var dicts_and_methods
512     num_of_d_and_ms         = length dicts_and_methods
513
514 dsExpr (ClassDictLam dicts methods expr)
515   = dsExpr expr         `thenDs` \ core_expr ->
516     case num_of_d_and_ms of
517         0 -> newSysLocalDs voidTy `thenDs` \ new_x ->
518              returnDs (mkValLam [new_x] core_expr)
519
520         1 -> -- no untupling
521             returnDs (mkValLam dicts_and_methods core_expr)
522
523         _ ->                            -- untuple it
524             newSysLocalDs tuple_ty `thenDs` \ new_x ->
525             returnDs (
526               Lam (ValBinder new_x)
527                 (Case (Var new_x)
528                     (AlgAlts
529                         [(tuple_con, dicts_and_methods, core_expr)]
530                         NoDefault)))
531   where
532     num_of_d_and_ms         = length dicts + length methods
533     dicts_and_methods       = dicts ++ methods
534     tuple_ty                = mkTupleTy  num_of_d_and_ms (map idType dicts_and_methods)
535     tuple_con               = tupleCon   num_of_d_and_ms
536
537 #ifdef DEBUG
538 -- HsSyn constructs that just shouldn't be here:
539 dsExpr (HsDo _ _)           = panic "dsExpr:HsDo"
540 dsExpr (ExplicitList _)     = panic "dsExpr:ExplicitList"
541 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
542 dsExpr (ArithSeqIn _)       = panic "dsExpr:ArithSeqIn"
543 #endif
544
545 out_of_range_msg                           -- ditto
546   = " out of range: [" ++ show minInt ++ ", " ++ show maxInt ++ "]\n"
547 \end{code}
548
549 %--------------------------------------------------------------------
550
551 @(dsApp e [t_1,..,t_n, e_1,..,e_n])@ returns something with the same
552 value as:
553 \begin{verbatim}
554 e t_1 ... t_n  e_1 .. e_n
555 \end{verbatim}
556
557 We're doing all this so we can saturate constructors (as painlessly as
558 possible).
559
560 \begin{code}
561 dsApp :: TypecheckedHsExpr      -- expr to desugar
562       -> [DsCoreArg]            -- accumulated ty/val args: NB:
563       -> DsM CoreExpr   -- final result
564
565 dsApp (HsApp e1 e2) args
566   = dsExpr e2                   `thenDs` \ core_e2 ->
567     dsApp  e1 (VarArg core_e2 : args)
568
569 dsApp (OpApp e1 op e2) args
570   = dsExpr e1                   `thenDs` \ core_e1 ->
571     dsExpr e2                   `thenDs` \ core_e2 ->
572     dsApp  op (VarArg core_e1 : VarArg core_e2 : args)
573
574 dsApp (DictApp expr dicts) args
575   =     -- now, those dicts may have been substituted away...
576     zipWithDs lookupEnvWithDefaultDs dicts (map Var dicts)
577                                 `thenDs` \ core_dicts ->
578     dsApp expr (map VarArg core_dicts ++ args)
579
580 dsApp (TyApp expr tys) args
581   = dsApp expr (map TyArg tys ++ args)
582
583 -- we might should look out for SectionLs, etc., here, but we don't
584
585 dsApp (HsVar v) args
586   = lookupEnvDs v       `thenDs` \ maybe_expr ->
587     mkAppDs (case maybe_expr of { Nothing -> Var v; Just expr -> expr }) args
588
589 dsApp anything_else args
590   = dsExpr anything_else        `thenDs` \ core_expr ->
591     mkAppDs core_expr args
592 \end{code}
593
594 \begin{code}
595 dsRbinds :: TypecheckedRecordBinds              -- The field bindings supplied
596          -> ([(Id, CoreArg)] -> DsM CoreExpr)   -- A continuation taking the field
597                                                 -- bindings with atomic rhss
598          -> DsM CoreExpr                        -- The result of the continuation,
599                                                 -- wrapped in suitable Lets
600
601 dsRbinds [] continue_with 
602   = continue_with []
603
604 dsRbinds ((sel_id, rhs, pun_flag) : rbinds) continue_with
605   = dsExpr rhs           `thenDs` \ rhs' ->
606     dsExprToAtom (VarArg rhs')  $ \ rhs_atom ->
607     dsRbinds rbinds             $ \ rbinds' ->
608     continue_with ((sel_id, rhs_atom) : rbinds')
609 \end{code}      
610
611 \begin{code}
612 -- do_unfold ty_env val_env (Lam (TyBinder tyvar) body) (TyArg ty : args)
613 --   = do_unfold (addOneToTyVarEnv ty_env tyvar ty) val_env body args
614 -- 
615 -- do_unfold ty_env val_env (Lam (ValBinder binder) body) (arg@(VarArg expr) : args)
616 --   = dsExprToAtom arg  $ \ arg_atom ->
617 --     do_unfold ty_env
618 --      (addOneToIdEnv val_env binder (argToExpr arg_atom))
619 --            body args
620 --
621 -- do_unfold ty_env val_env body args
622 --   =  -- Clone the remaining part of the template
623 --    uniqSMtoDsM (substCoreExpr val_env ty_env body)   `thenDs` \ body' ->
624 --
625 --      -- Apply result to remaining arguments
626 --    mkAppDs body' args
627 \end{code}
628
629 Basically does the translation given in the Haskell~1.3 report:
630 \begin{code}
631 dsDo    :: Id           -- id for: (>>=) m
632         -> Id           -- id for: zero m
633         -> [TypecheckedStmt]
634         -> DsM CoreExpr
635
636 dsDo then_id zero_id (stmt:stmts)
637   = case stmt of
638       ExprStmt expr locn -> ASSERT( null stmts ) do_expr expr locn
639
640       ExprStmtOut expr locn a b -> 
641         do_expr expr locn               `thenDs` \ expr2 ->
642         ds_rest                         `thenDs` \ rest  ->
643         newSysLocalDs a                 `thenDs` \ ignored_result_id ->
644         dsApp (HsVar then_id) [TyArg a, TyArg b, VarArg expr2, 
645                                VarArg (mkValLam [ignored_result_id] rest)]
646
647       LetStmt binds ->
648         dsBinds False binds     `thenDs` \ binds2 ->
649         ds_rest                 `thenDs` \ rest   ->
650         returnDs (mkCoLetsAny binds2 rest)
651
652       BindStmtOut pat expr locn a b ->
653         do_expr expr locn   `thenDs` \ expr2 ->
654         let
655             zero_expr = TyApp (HsVar zero_id) [b]
656             main_match
657               = PatMatch pat (SimpleMatch (HsDoOut stmts then_id zero_id locn))
658             the_matches
659               = if failureFreePat pat
660                 then [main_match]
661                 else [main_match, PatMatch (WildPat a) (SimpleMatch zero_expr)]
662         in
663         matchWrapper DoBindMatch the_matches "`do' statement"
664                             `thenDs` \ (binders, matching_code) ->
665         dsApp (HsVar then_id) [TyArg a, TyArg b,
666                                VarArg expr2, VarArg (mkValLam binders matching_code)]
667   where
668     ds_rest = dsDo then_id zero_id stmts
669     do_expr expr locn = putSrcLocDs locn (dsExpr expr)
670
671 #ifdef DEBUG
672 dsDo then_expr zero_expr [] = panic "dsDo:[]"
673 #endif
674 \end{code}