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