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