4f2760ec479e9650aac5fe47de9e97d0d781a2a2
[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, PolyType,
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 CoreUnfold       ( Unfolding )
36 import CoreUtils        ( coreExprType, substCoreExpr, argToExpr,
37                           mkCoreIfThenElse, unTagBinders )
38 import CostCentre       ( mkUserCC )
39 import FieldLabel       ( fieldLabelType, FieldLabel )
40 import Id               ( mkTupleCon, idType, nullIdEnv, addOneToIdEnv,
41                           getIdUnfolding, dataConArgTys, dataConFieldLabels,
42                           recordSelectorFieldLabel
43                         )
44 import Literal          ( mkMachInt, Literal(..) )
45 import MagicUFs         ( MagicUnfoldingFun )
46 import Name             ( Name{--O only-} )
47 import PprStyle         ( PprStyle(..) )
48 import PprType          ( GenType )
49 import PrelVals         ( rEC_CON_ERROR_ID, rEC_UPD_ERROR_ID, voidId )
50 import Pretty           ( ppShow, ppBesides, ppPStr, ppStr )
51 import TyCon            ( isDataTyCon, isNewTyCon )
52 import Type             ( splitSigmaTy, splitFunTy, typePrimRep,
53                           getAppDataTyConExpandingDicts, getAppTyCon, applyTy,
54                           maybeBoxedPrimType
55                         )
56 import TysPrim          ( voidTy )
57 import TysWiredIn       ( mkTupleTy, nilDataCon, consDataCon,
58                           charDataCon, charTy
59                         )
60 import TyVar            ( nullTyVarEnv, addOneToTyVarEnv, GenTyVar{-instance Eq-} )
61 import Usage            ( SYN_IE(UVar) )
62 import Util             ( zipEqual, pprError, panic, assertPanic )
63
64 mk_nil_con ty = mkCon nilDataCon [] [ty] []  -- micro utility...
65 \end{code}
66
67 The funny business to do with variables is that we look them up in the
68 Id-to-Id and Id-to-Id maps that the monadery is carrying
69 around; if we get hits, we use the value accordingly.
70
71 %************************************************************************
72 %*                                                                      *
73 \subsection[DsExpr-vars-and-cons]{Variables and constructors}
74 %*                                                                      *
75 %************************************************************************
76
77 \begin{code}
78 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
79
80 dsExpr e@(HsVar var) = dsApp e []
81 \end{code}
82
83 %************************************************************************
84 %*                                                                      *
85 \subsection[DsExpr-literals]{Literals}
86 %*                                                                      *
87 %************************************************************************
88
89 We give int/float literals type Integer and Rational, respectively.
90 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
91 around them.
92
93 ToDo: put in range checks for when converting "i"
94 (or should that be in the typechecker?)
95
96 For numeric literals, we try to detect there use at a standard type
97 (Int, Float, etc.) are directly put in the right constructor.
98 [NB: down with the @App@ conversion.]
99 Otherwise, we punt, putting in a "NoRep" Core literal (where the
100 representation decisions are delayed)...
101
102 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
103
104 \begin{code}
105 dsExpr (HsLitOut (HsString s) _)
106   | _NULL_ s
107   = returnDs (mk_nil_con charTy)
108
109   | _LENGTH_ s == 1
110   = let
111         the_char = mkCon charDataCon [] [] [LitArg (MachChar (_HEAD_ s))]
112         the_nil  = mk_nil_con charTy
113     in
114     mkConDs consDataCon [TyArg charTy, VarArg the_char, VarArg the_nil]
115
116 -- "_" => build (\ c n -> c 'c' n)      -- LATER
117
118 -- "str" ==> build (\ c n -> foldr charTy T c n "str")
119
120 {- LATER:
121 dsExpr (HsLitOut (HsString str) _)
122   = newTyVarsDs [alphaTyVar]            `thenDs` \ [new_tyvar] ->
123     let
124         new_ty = mkTyVarTy new_tyvar
125     in
126     newSysLocalsDs [
127                 charTy `mkFunTy` (new_ty `mkFunTy` new_ty),
128                 new_ty,
129                        mkForallTy [alphaTyVar]
130                                ((charTy `mkFunTy` (alphaTy `mkFunTy` alphaTy))
131                                         `mkFunTy` (alphaTy `mkFunTy` alphaTy))
132                 ]                       `thenDs` \ [c,n,g] ->
133      returnDs (mkBuild charTy new_tyvar c n g (
134         foldl App
135           (CoTyApp (CoTyApp (Var foldrId) charTy) new_ty) *** ensure non-prim type ***
136           [VarArg c,VarArg n,LitArg (NoRepStr str)]))
137 -}
138
139 -- otherwise, leave it as a NoRepStr;
140 -- the Core-to-STG pass will wrap it in an application of "unpackCStringId".
141
142 dsExpr (HsLitOut (HsString str) _)
143   = returnDs (Lit (NoRepStr str))
144
145 dsExpr (HsLitOut (HsLitLit s) ty)
146   = returnDs ( mkCon data_con [] [] [LitArg (MachLitLit s kind)] )
147   where
148     (data_con, kind)
149       = case (maybeBoxedPrimType ty) of
150           Just (boxing_data_con, prim_ty)
151             -> (boxing_data_con, typePrimRep prim_ty)
152           Nothing
153             -> pprError "ERROR: ``literal-literal'' not a single-constructor type: "
154                         (ppBesides [ppPStr s, ppStr "; type: ", ppr PprDebug ty])
155
156 dsExpr (HsLitOut (HsInt i) ty)
157   = returnDs (Lit (NoRepInteger i ty))
158
159 dsExpr (HsLitOut (HsFrac r) ty)
160   = returnDs (Lit (NoRepRational r ty))
161
162 -- others where we know what to do:
163
164 dsExpr (HsLitOut (HsIntPrim i) _)
165   = if (i >= toInteger minInt && i <= toInteger maxInt) then
166         returnDs (Lit (mkMachInt i))
167     else
168         error ("ERROR: Int constant " ++ show i ++ out_of_range_msg)
169
170 dsExpr (HsLitOut (HsFloatPrim f) _)
171   = returnDs (Lit (MachFloat f))
172     -- ToDo: range checking needed!
173
174 dsExpr (HsLitOut (HsDoublePrim d) _)
175   = returnDs (Lit (MachDouble d))
176     -- ToDo: range checking needed!
177
178 dsExpr (HsLitOut (HsChar c) _)
179   = returnDs ( mkCon charDataCon [] [] [LitArg (MachChar c)] )
180
181 dsExpr (HsLitOut (HsCharPrim c) _)
182   = returnDs (Lit (MachChar c))
183
184 dsExpr (HsLitOut (HsStringPrim s) _)
185   = returnDs (Lit (MachStr s))
186
187 -- end of literals magic. --
188
189 dsExpr expr@(HsLam a_Match)
190   = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
191     returnDs ( mkValLam binders matching_code )
192
193 dsExpr expr@(HsApp e1 e2)    = dsApp expr []
194 dsExpr expr@(OpApp e1 op e2) = dsApp expr []
195 \end{code}
196
197 Operator sections.  At first it looks as if we can convert
198 \begin{verbatim}
199         (expr op)
200 \end{verbatim}
201 to
202 \begin{verbatim}
203         \x -> op expr x
204 \end{verbatim}
205
206 But no!  expr might be a redex, and we can lose laziness badly this
207 way.  Consider
208 \begin{verbatim}
209         map (expr op) xs
210 \end{verbatim}
211 for example.  So we convert instead to
212 \begin{verbatim}
213         let y = expr in \x -> op y x
214 \end{verbatim}
215 If \tr{expr} is actually just a variable, say, then the simplifier
216 will sort it out.
217
218 \begin{code}
219 dsExpr (SectionL expr op)
220   = dsExpr op                   `thenDs` \ core_op ->
221     dsExpr expr                 `thenDs` \ core_expr ->
222     dsExprToAtom (VarArg core_expr)     $ \ y_atom ->
223
224     -- for the type of x, we need the type of op's 2nd argument
225     let
226         x_ty  = case (splitSigmaTy (coreExprType core_op)) of { (_, _, tau_ty) ->
227                 case (splitFunTy tau_ty)                   of {
228                   ((_:arg2_ty:_), _) -> arg2_ty;
229                   _ -> panic "dsExpr:SectionL:arg 2 ty" }}
230     in
231     newSysLocalDs x_ty          `thenDs` \ x_id ->
232     returnDs (mkValLam [x_id] (core_op `App` y_atom `App` VarArg x_id)) 
233
234 -- dsExpr (SectionR op expr)    -- \ x -> op x expr
235 dsExpr (SectionR op expr)
236   = dsExpr op                   `thenDs` \ core_op ->
237     dsExpr expr                 `thenDs` \ core_expr ->
238     dsExprToAtom (VarArg core_expr)     $ \ y_atom ->
239
240     -- for the type of x, we need the type of op's 1st argument
241     let
242         x_ty  = case (splitSigmaTy (coreExprType core_op)) of { (_, _, tau_ty) ->
243                 case (splitFunTy tau_ty)                   of {
244                   ((arg1_ty:_), _) -> arg1_ty;
245                   _ -> panic "dsExpr:SectionR:arg 1 ty" }}
246     in
247     newSysLocalDs x_ty          `thenDs` \ x_id ->
248     returnDs (mkValLam [x_id] (core_op `App` VarArg x_id `App` y_atom))
249
250 dsExpr (CCall label args may_gc is_asm result_ty)
251   = mapDs dsExpr args           `thenDs` \ core_args ->
252     dsCCall label core_args may_gc is_asm result_ty
253         -- dsCCall does all the unboxification, etc.
254
255 dsExpr (HsSCC cc expr)
256   = dsExpr expr                 `thenDs` \ core_expr ->
257     getModuleAndGroupDs         `thenDs` \ (mod_name, group_name) ->
258     returnDs ( SCC (mkUserCC cc mod_name group_name) core_expr)
259
260 dsExpr expr@(HsCase discrim matches src_loc)
261   = putSrcLocDs src_loc $
262     dsExpr discrim                              `thenDs` \ core_discrim ->
263     matchWrapper CaseMatch matches "case"       `thenDs` \ ([discrim_var], matching_code) ->
264     returnDs ( mkCoLetAny (NonRec discrim_var core_discrim) matching_code )
265
266 dsExpr (ListComp expr quals)
267   = dsExpr expr `thenDs` \ core_expr ->
268     dsListComp core_expr quals
269
270 dsExpr (HsLet binds expr)
271   = dsBinds False binds `thenDs` \ core_binds ->
272     dsExpr expr         `thenDs` \ core_expr ->
273     returnDs ( mkCoLetsAny core_binds core_expr )
274
275 dsExpr (HsDoOut stmts then_id zero_id src_loc)
276   = putSrcLocDs src_loc $
277     dsDo then_id zero_id stmts
278
279 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
280   = putSrcLocDs src_loc $
281     dsExpr guard_expr   `thenDs` \ core_guard ->
282     dsExpr then_expr    `thenDs` \ core_then ->
283     dsExpr else_expr    `thenDs` \ core_else ->
284     returnDs (mkCoreIfThenElse core_guard core_then core_else)
285 \end{code}
286
287
288 Type lambda and application
289 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
290 \begin{code}
291 dsExpr (TyLam tyvars expr)
292   = dsExpr expr `thenDs` \ core_expr ->
293     returnDs (mkTyLam tyvars core_expr)
294
295 dsExpr expr@(TyApp e tys) = dsApp expr []
296 \end{code}
297
298
299 Various data construction things
300 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
301 \begin{code}
302 dsExpr (ExplicitListOut ty xs)
303   = case xs of
304       []     -> returnDs (mk_nil_con ty)
305       (y:ys) ->
306         dsExpr y                            `thenDs` \ core_hd  ->
307         dsExpr (ExplicitListOut ty ys)  `thenDs` \ core_tl  ->
308         mkConDs consDataCon [TyArg ty, VarArg core_hd, VarArg core_tl]
309
310 dsExpr (ExplicitTuple expr_list)
311   = mapDs dsExpr expr_list        `thenDs` \ core_exprs  ->
312     mkConDs (mkTupleCon (length expr_list))
313             (map (TyArg . coreExprType) core_exprs ++ map VarArg core_exprs)
314
315 -- Two cases, one for ordinary constructors and one for newtype constructors
316 dsExpr (HsCon con tys args)
317   | isDataTyCon tycon                   -- The usual datatype case
318   = mapDs dsExpr args   `thenDs` \ args_exprs ->
319     mkConDs con (map TyArg tys ++ map VarArg args_exprs)
320
321   | otherwise                           -- The newtype case
322   = ASSERT( isNewTyCon tycon )
323     ASSERT( null rest_args )
324     dsExpr first_arg            `thenDs` \ arg_expr ->
325     returnDs (Coerce (CoerceIn con) result_ty arg_expr)
326
327   where
328     (first_arg:rest_args) = args
329     (args_tys, result_ty) = splitFunTy (foldl applyTy (idType con) tys)
330     (tycon,_)             = getAppTyCon result_ty
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 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_ty               = coreExprType record_expr'
427         (tycon, inst_tys, cons) = trace "DsExpr.getAppDataTyConExpandingDicts" $
428                                   getAppDataTyConExpandingDicts record_ty
429         cons_to_upd             = filter has_all_fields cons
430
431         -- initial_args are passed to every constructor
432         initial_args            = map TyArg 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 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_ty                     `thenDs` \ deflt_id ->
453             mkErrorAppDs rEC_UPD_ERROR_ID record_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   = lookupEnvWithDefaultDs dict (Var dict)
495
496 dsExpr (Dictionary dicts methods)
497   = -- hey, these things may have been substituted away...
498     zipWithDs lookupEnvWithDefaultDs
499               dicts_and_methods dicts_and_methods_exprs
500                         `thenDs` \ core_d_and_ms ->
501
502     (case num_of_d_and_ms of
503       0 -> returnDs (Var voidId)
504
505       1 -> returnDs (head core_d_and_ms) -- just a single Id
506
507       _ ->          -- tuple 'em up
508            mkConDs (mkTupleCon num_of_d_and_ms)
509                    (map (TyArg . coreExprType) core_d_and_ms ++ map VarArg core_d_and_ms)
510     )
511   where
512     dicts_and_methods       = dicts ++ methods
513     dicts_and_methods_exprs = map Var dicts_and_methods
514     num_of_d_and_ms         = length dicts_and_methods
515
516 dsExpr (ClassDictLam dicts methods expr)
517   = dsExpr expr         `thenDs` \ core_expr ->
518     case num_of_d_and_ms of
519         0 -> newSysLocalDs voidTy `thenDs` \ new_x ->
520              returnDs (mkValLam [new_x] core_expr)
521
522         1 -> -- no untupling
523             returnDs (mkValLam dicts_and_methods core_expr)
524
525         _ ->                            -- untuple it
526             newSysLocalDs tuple_ty `thenDs` \ new_x ->
527             returnDs (
528               Lam (ValBinder new_x)
529                 (Case (Var new_x)
530                     (AlgAlts
531                         [(tuple_con, dicts_and_methods, core_expr)]
532                         NoDefault)))
533   where
534     num_of_d_and_ms         = length dicts + length methods
535     dicts_and_methods       = dicts ++ methods
536     tuple_ty                = mkTupleTy    num_of_d_and_ms (map idType dicts_and_methods)
537     tuple_con               = mkTupleCon   num_of_d_and_ms
538
539 #ifdef DEBUG
540 -- HsSyn constructs that just shouldn't be here:
541 dsExpr (HsDo _ _)           = panic "dsExpr:HsDo"
542 dsExpr (ExplicitList _)     = panic "dsExpr:ExplicitList"
543 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
544 dsExpr (ArithSeqIn _)       = panic "dsExpr:ArithSeqIn"
545 #endif
546
547 out_of_range_msg                           -- ditto
548   = " out of range: [" ++ show minInt ++ ", " ++ show maxInt ++ "]\n"
549 \end{code}
550
551 %--------------------------------------------------------------------
552
553 @(dsApp e [t_1,..,t_n, e_1,..,e_n])@ returns something with the same
554 value as:
555 \begin{verbatim}
556 e t_1 ... t_n  e_1 .. e_n
557 \end{verbatim}
558
559 We're doing all this so we can saturate constructors (as painlessly as
560 possible).
561
562 \begin{code}
563 dsApp :: TypecheckedHsExpr      -- expr to desugar
564       -> [DsCoreArg]            -- accumulated ty/val args: NB:
565       -> DsM CoreExpr   -- final result
566
567 dsApp (HsApp e1 e2) args
568   = dsExpr e2                   `thenDs` \ core_e2 ->
569     dsApp  e1 (VarArg core_e2 : args)
570
571 dsApp (OpApp e1 op e2) args
572   = dsExpr e1                   `thenDs` \ core_e1 ->
573     dsExpr e2                   `thenDs` \ core_e2 ->
574     dsApp  op (VarArg core_e1 : VarArg core_e2 : args)
575
576 dsApp (DictApp expr dicts) args
577   =     -- now, those dicts may have been substituted away...
578     zipWithDs lookupEnvWithDefaultDs dicts (map Var dicts)
579                                 `thenDs` \ core_dicts ->
580     dsApp expr (map VarArg core_dicts ++ args)
581
582 dsApp (TyApp expr tys) args
583   = dsApp expr (map TyArg tys ++ args)
584
585 -- we might should look out for SectionLs, etc., here, but we don't
586
587 dsApp (HsVar v) args
588   = lookupEnvDs v       `thenDs` \ maybe_expr ->
589     mkAppDs (case maybe_expr of { Nothing -> Var v; Just expr -> expr }) args
590
591 dsApp anything_else args
592   = dsExpr anything_else        `thenDs` \ core_expr ->
593     mkAppDs core_expr args
594 \end{code}
595
596 \begin{code}
597 dsRbinds :: TypecheckedRecordBinds              -- The field bindings supplied
598          -> ([(Id, CoreArg)] -> DsM CoreExpr)   -- A continuation taking the field
599                                                 -- bindings with atomic rhss
600          -> DsM CoreExpr                        -- The result of the continuation,
601                                                 -- wrapped in suitable Lets
602
603 dsRbinds [] continue_with 
604   = continue_with []
605
606 dsRbinds ((sel_id, rhs, pun_flag) : rbinds) continue_with
607   = dsExpr rhs           `thenDs` \ rhs' ->
608     dsExprToAtom (VarArg rhs')  $ \ rhs_atom ->
609     dsRbinds rbinds             $ \ rbinds' ->
610     continue_with ((sel_id, rhs_atom) : rbinds')
611 \end{code}      
612
613 \begin{code}
614 -- do_unfold ty_env val_env (Lam (TyBinder tyvar) body) (TyArg ty : args)
615 --   = do_unfold (addOneToTyVarEnv ty_env tyvar ty) val_env body args
616 -- 
617 -- do_unfold ty_env val_env (Lam (ValBinder binder) body) (arg@(VarArg expr) : args)
618 --   = dsExprToAtom arg  $ \ arg_atom ->
619 --     do_unfold ty_env
620 --      (addOneToIdEnv val_env binder (argToExpr arg_atom))
621 --            body args
622 --
623 -- do_unfold ty_env val_env body args
624 --   =  -- Clone the remaining part of the template
625 --    uniqSMtoDsM (substCoreExpr val_env ty_env body)   `thenDs` \ body' ->
626 --
627 --      -- Apply result to remaining arguments
628 --    mkAppDs body' args
629 \end{code}
630
631 Basically does the translation given in the Haskell~1.3 report:
632 \begin{code}
633 dsDo    :: Id           -- id for: (>>=) m
634         -> Id           -- id for: zero m
635         -> [TypecheckedStmt]
636         -> DsM CoreExpr
637
638 dsDo then_id zero_id (stmt:stmts)
639   = case stmt of
640       ExprStmt expr locn -> ASSERT( null stmts ) do_expr expr locn
641
642       ExprStmtOut expr locn a b -> 
643         do_expr expr locn               `thenDs` \ expr2 ->
644         ds_rest                         `thenDs` \ rest  ->
645         newSysLocalDs a                 `thenDs` \ ignored_result_id ->
646         dsApp (HsVar then_id) [TyArg a, TyArg b, VarArg expr2, 
647                                VarArg (mkValLam [ignored_result_id] rest)]
648
649       LetStmt binds ->
650         dsBinds False binds     `thenDs` \ binds2 ->
651         ds_rest                 `thenDs` \ rest   ->
652         returnDs (mkCoLetsAny binds2 rest)
653
654       BindStmtOut pat expr locn a b ->
655         do_expr expr locn   `thenDs` \ expr2 ->
656         let
657             zero_expr = TyApp (HsVar zero_id) [b]
658             main_match
659               = PatMatch pat (SimpleMatch (HsDoOut stmts then_id zero_id locn))
660             the_matches
661               = if failureFreePat pat
662                 then [main_match]
663                 else [main_match, PatMatch (WildPat a) (SimpleMatch zero_expr)]
664         in
665         matchWrapper DoBindMatch the_matches "`do' statement"
666                             `thenDs` \ (binders, matching_code) ->
667         dsApp (HsVar then_id) [TyArg a, TyArg b,
668                                VarArg expr2, VarArg (mkValLam binders matching_code)]
669   where
670     ds_rest = dsDo then_id zero_id stmts
671     do_expr expr locn = putSrcLocDs locn (dsExpr expr)
672
673 #ifdef DEBUG
674 dsDo then_expr zero_expr [] = panic "dsDo:[]"
675 #endif
676 \end{code}