9030f94c3499e8d429e418dbae5ef4d59ead484d
[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 import Ubiq
12 import DsLoop           -- partly to get dsBinds, partly to chk dsExpr
13
14 import HsSyn            ( HsExpr(..), HsLit(..), ArithSeqInfo(..),
15                           Match, Qual, HsBinds, Stmt, PolyType )
16 import TcHsSyn          ( TypecheckedHsExpr(..), TypecheckedHsBinds(..),
17                           TypecheckedRecordBinds(..), TypecheckedPat(..)
18                         )
19 import CoreSyn
20
21 import DsMonad
22 import DsCCall          ( dsCCall )
23 import DsListComp       ( dsListComp )
24 import DsUtils          ( mkAppDs, mkConDs, mkPrimDs, dsExprToAtom,
25                           mkErrorAppDs, showForErr, EquationInfo,
26                           MatchResult
27                         )
28 import Match            ( matchWrapper )
29
30 import CoreUnfold       ( UnfoldingDetails(..), UnfoldingGuidance(..),
31                           FormSummary )
32 import CoreUtils        ( coreExprType, substCoreExpr, argToExpr,
33                           mkCoreIfThenElse, unTagBinders )
34 import CostCentre       ( mkUserCC )
35 import FieldLabel       ( fieldLabelType, FieldLabel )
36 import Id               ( mkTupleCon, idType, nullIdEnv, addOneToIdEnv,
37                           getIdUnfolding, dataConArgTys, dataConFieldLabels,
38                           recordSelectorFieldLabel
39                         )
40 import Literal          ( mkMachInt, Literal(..) )
41 import MagicUFs         ( MagicUnfoldingFun )
42 import Name             ( Name{--O only-} )
43 import PprStyle         ( PprStyle(..) )
44 import PprType          ( GenType )
45 import PrelInfo         ( mkTupleTy, unitTy, nilDataCon, consDataCon,
46                           charDataCon, charTy, rEC_CON_ERROR_ID,
47                           rEC_UPD_ERROR_ID
48                         )
49 import Pretty           ( ppShow, ppBesides, ppPStr, ppStr )
50 import TyCon            ( isDataTyCon, isNewTyCon )
51 import Type             ( splitSigmaTy, splitFunTy, typePrimRep,
52                           getAppDataTyCon, getAppTyCon, applyTy
53                         )
54 import TyVar            ( nullTyVarEnv, addOneToTyVarEnv, GenTyVar{-instance Eq-} )
55 import Usage            ( UVar(..) )
56 import Util             ( zipEqual, pprError, panic, assertPanic )
57
58 maybeBoxedPrimType = panic "DsExpr.maybeBoxedPrimType"
59 splitTyArgs = panic "DsExpr.splitTyArgs"
60
61 mk_nil_con ty = mkCon nilDataCon [] [ty] []  -- micro utility...
62 \end{code}
63
64 The funny business to do with variables is that we look them up in the
65 Id-to-Id and Id-to-Id maps that the monadery is carrying
66 around; if we get hits, we use the value accordingly.
67
68 %************************************************************************
69 %*                                                                      *
70 \subsection[DsExpr-vars-and-cons]{Variables and constructors}
71 %*                                                                      *
72 %************************************************************************
73
74 \begin{code}
75 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
76
77 dsExpr (HsVar var) = dsApp (HsVar var) []
78 \end{code}
79
80 %************************************************************************
81 %*                                                                      *
82 \subsection[DsExpr-literals]{Literals}
83 %*                                                                      *
84 %************************************************************************
85
86 We give int/float literals type Integer and Rational, respectively.
87 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
88 around them.
89
90 ToDo: put in range checks for when converting "i"
91 (or should that be in the typechecker?)
92
93 For numeric literals, we try to detect there use at a standard type
94 (Int, Float, etc.) are directly put in the right constructor.
95 [NB: down with the @App@ conversion.]
96 Otherwise, we punt, putting in a "NoRep" Core literal (where the
97 representation decisions are delayed)...
98
99 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
100
101 \begin{code}
102 dsExpr (HsLitOut (HsString s) _)
103   | _NULL_ s
104   = returnDs (mk_nil_con charTy)
105
106   | _LENGTH_ s == 1
107   = let
108         the_char = mkCon charDataCon [] [] [LitArg (MachChar (_HEAD_ s))]
109         the_nil  = mk_nil_con charTy
110     in
111     mkConDs consDataCon [charTy] [the_char, the_nil]
112
113 -- "_" => build (\ c n -> c 'c' n)      -- LATER
114
115 -- "str" ==> build (\ c n -> foldr charTy T c n "str")
116
117 {- LATER:
118 dsExpr (HsLitOut (HsString str) _)
119   = newTyVarsDs [alphaTyVar]            `thenDs` \ [new_tyvar] ->
120     let
121         new_ty = mkTyVarTy new_tyvar
122     in
123     newSysLocalsDs [
124                 charTy `mkFunTy` (new_ty `mkFunTy` new_ty),
125                 new_ty,
126                        mkForallTy [alphaTyVar]
127                                ((charTy `mkFunTy` (alphaTy `mkFunTy` alphaTy))
128                                         `mkFunTy` (alphaTy `mkFunTy` alphaTy))
129                 ]                       `thenDs` \ [c,n,g] ->
130      returnDs (mkBuild charTy new_tyvar c n g (
131         foldl App
132           (CoTyApp (CoTyApp (Var foldrId) charTy) new_ty) *** ensure non-prim type ***
133           [VarArg c,VarArg n,LitArg (NoRepStr str)]))
134 -}
135
136 -- otherwise, leave it as a NoRepStr;
137 -- the Core-to-STG pass will wrap it in an application of "unpackCStringId".
138
139 dsExpr (HsLitOut (HsString str) _)
140   = returnDs (Lit (NoRepStr str))
141
142 dsExpr (HsLitOut (HsLitLit s) ty)
143   = returnDs ( mkCon data_con [] [] [LitArg (MachLitLit s kind)] )
144   where
145     (data_con, kind)
146       = case (maybeBoxedPrimType ty) of
147           Just (boxing_data_con, prim_ty)
148             -> (boxing_data_con, typePrimRep prim_ty)
149           Nothing
150             -> pprError "ERROR: ``literal-literal'' not a single-constructor type: "
151                         (ppBesides [ppPStr s, ppStr "; type: ", ppr PprDebug ty])
152
153 dsExpr (HsLitOut (HsInt i) _)
154   = returnDs (Lit (NoRepInteger i))
155
156 dsExpr (HsLitOut (HsFrac r) _)
157   = returnDs (Lit (NoRepRational r))
158
159 -- others where we know what to do:
160
161 dsExpr (HsLitOut (HsIntPrim i) _)
162   = if (i >= toInteger minInt && i <= toInteger maxInt) then
163         returnDs (Lit (mkMachInt i))
164     else
165         error ("ERROR: Int constant " ++ show i ++ out_of_range_msg)
166
167 dsExpr (HsLitOut (HsFloatPrim f) _)
168   = returnDs (Lit (MachFloat f))
169     -- ToDo: range checking needed!
170
171 dsExpr (HsLitOut (HsDoublePrim d) _)
172   = returnDs (Lit (MachDouble d))
173     -- ToDo: range checking needed!
174
175 dsExpr (HsLitOut (HsChar c) _)
176   = returnDs ( mkCon charDataCon [] [] [LitArg (MachChar c)] )
177
178 dsExpr (HsLitOut (HsCharPrim c) _)
179   = returnDs (Lit (MachChar c))
180
181 dsExpr (HsLitOut (HsStringPrim s) _)
182   = returnDs (Lit (MachStr s))
183
184 -- end of literals magic. --
185
186 dsExpr expr@(HsLam a_Match)
187   = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
188     returnDs ( mkValLam binders matching_code )
189
190 dsExpr expr@(HsApp e1 e2)    = dsApp expr []
191 dsExpr expr@(OpApp e1 op e2) = dsApp expr []
192 \end{code}
193
194 Operator sections.  At first it looks as if we can convert
195 \begin{verbatim}
196         (expr op)
197 \end{verbatim}
198 to
199 \begin{verbatim}
200         \x -> op expr x
201 \end{verbatim}
202
203 But no!  expr might be a redex, and we can lose laziness badly this
204 way.  Consider
205 \begin{verbatim}
206         map (expr op) xs
207 \end{verbatim}
208 for example.  So we convert instead to
209 \begin{verbatim}
210         let y = expr in \x -> op y x
211 \end{verbatim}
212 If \tr{expr} is actually just a variable, say, then the simplifier
213 will sort it out.
214
215 \begin{code}
216 dsExpr (SectionL expr op)
217   = dsExpr op                   `thenDs` \ core_op ->
218     dsExpr expr                 `thenDs` \ core_expr ->
219     dsExprToAtom core_expr      $ \ y_atom ->
220
221     -- for the type of x, we need the type of op's 2nd argument
222     let
223         x_ty  = case (splitSigmaTy (coreExprType core_op)) of { (_, _, tau_ty) ->
224                 case (splitTyArgs tau_ty)                 of {
225                   ((_:arg2_ty:_), _) -> arg2_ty;
226                   _ -> panic "dsExpr:SectionL:arg 2 ty"
227                 }}
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 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 (splitTyArgs tau_ty)                 of {
242                   ((arg1_ty:_), _) -> arg1_ty;
243                   _ -> panic "dsExpr:SectionR:arg 1 ty"
244                 }}
245     in
246     newSysLocalDs x_ty          `thenDs` \ x_id ->
247     returnDs (mkValLam [x_id] (core_op `App` VarArg x_id `App` y_atom))
248
249 dsExpr (CCall label args may_gc is_asm result_ty)
250   = mapDs dsExpr args           `thenDs` \ core_args ->
251     dsCCall label core_args may_gc is_asm result_ty
252         -- dsCCall does all the unboxification, etc.
253
254 dsExpr (HsSCC cc expr)
255   = dsExpr expr                 `thenDs` \ core_expr ->
256     getModuleAndGroupDs         `thenDs` \ (mod_name, group_name) ->
257     returnDs ( SCC (mkUserCC cc mod_name group_name) core_expr)
258
259 dsExpr expr@(HsCase discrim matches src_loc)
260   = putSrcLocDs src_loc $
261     dsExpr discrim                              `thenDs` \ core_discrim ->
262     matchWrapper CaseMatch matches "case"       `thenDs` \ ([discrim_var], matching_code) ->
263     returnDs ( mkCoLetAny (NonRec discrim_var core_discrim) matching_code )
264
265 dsExpr (ListComp expr quals)
266   = dsExpr expr `thenDs` \ core_expr ->
267     dsListComp core_expr quals
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 stmts m_id mz_id src_loc)
275   = putSrcLocDs src_loc $
276     panic "dsExpr:HsDoOut"
277
278 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
279   = putSrcLocDs src_loc $
280     dsExpr guard_expr   `thenDs` \ core_guard ->
281     dsExpr then_expr    `thenDs` \ core_then ->
282     dsExpr else_expr    `thenDs` \ core_else ->
283     returnDs (mkCoreIfThenElse core_guard core_then core_else)
284
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 [ty] [core_hd, core_tl]
309
310 dsExpr (ExplicitTuple expr_list)
311   = mapDs dsExpr expr_list        `thenDs` \ core_exprs  ->
312     mkConDs (mkTupleCon (length expr_list))
313             (map coreExprType core_exprs)
314             core_exprs
315
316 -- Two cases, one for ordinary constructors and one for newtype constructors
317 dsExpr (HsCon con tys args)
318   | isDataTyCon tycon                   -- The usual datatype case
319   = mapDs dsExpr args   `thenDs` \ args_exprs ->
320     mkConDs con tys args_exprs
321
322   | otherwise                           -- The newtype case
323   = ASSERT( isNewTyCon tycon )
324     ASSERT( null rest_args )
325     dsExpr first_arg            `thenDs` \ arg_expr ->
326     returnDs (Coerce (CoerceIn con) result_ty arg_expr)
327
328   where
329     (first_arg:rest_args) = args
330     (args_tys, result_ty) = splitFunTy (foldl applyTy (idType con) tys)
331     (tycon,_)             = getAppTyCon result_ty
332
333 dsExpr (ArithSeqOut expr (From from))
334   = dsExpr expr           `thenDs` \ expr2 ->
335     dsExpr from           `thenDs` \ from2 ->
336     mkAppDs expr2 [] [from2]
337
338 dsExpr (ArithSeqOut expr (FromTo from two))
339   = dsExpr expr           `thenDs` \ expr2 ->
340     dsExpr from           `thenDs` \ from2 ->
341     dsExpr two            `thenDs` \ two2 ->
342     mkAppDs expr2 [] [from2, two2]
343
344 dsExpr (ArithSeqOut expr (FromThen from thn))
345   = dsExpr expr           `thenDs` \ expr2 ->
346     dsExpr from           `thenDs` \ from2 ->
347     dsExpr thn            `thenDs` \ thn2 ->
348     mkAppDs expr2 [] [from2, thn2]
349
350 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
351   = dsExpr expr           `thenDs` \ expr2 ->
352     dsExpr from           `thenDs` \ from2 ->
353     dsExpr thn            `thenDs` \ thn2 ->
354     dsExpr two            `thenDs` \ two2 ->
355     mkAppDs expr2 [] [from2, thn2, two2]
356 \end{code}
357
358 Record construction and update
359 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
360 For record construction we do this (assuming T has three arguments)
361
362         T { op2 = e }
363 ==>
364         let err = /\a -> recConErr a 
365         T (recConErr t1 "M.lhs/230/op1") 
366           e 
367           (recConErr t1 "M.lhs/230/op3")
368
369 recConErr then converts its arugment string into a proper message
370 before printing it as
371
372         M.lhs, line 230: missing field op1 was evaluated
373
374
375 \begin{code}
376 dsExpr (RecordCon con_expr rbinds)
377   = dsExpr con_expr     `thenDs` \ con_expr' ->
378     let
379         con_id       = get_con con_expr'
380         (arg_tys, _) = splitFunTy (coreExprType con_expr')
381
382         mk_arg (arg_ty, lbl)
383           = case [rhs | (sel_id,rhs,_) <- rbinds,
384                         lbl == recordSelectorFieldLabel sel_id] of
385               (rhs:rhss) -> ASSERT( null rhss )
386                             dsExpr rhs
387               []         -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showForErr lbl)
388     in
389     mapDs mk_arg (arg_tys `zipEqual` dataConFieldLabels con_id) `thenDs` \ con_args ->
390     mkAppDs con_expr' [] con_args
391   where
392         -- "con_expr'" is simply an application of the constructor Id
393         -- to types and (perhaps) dictionaries. This gets the constructor...
394     get_con (Var con)   = con
395     get_con (App fun _) = get_con fun
396 \end{code}
397
398 Record update is a little harder. Suppose we have the decl:
399
400         data T = T1 {op1, op2, op3 :: Int}
401                | T2 {op4, op2 :: Int}
402                | T3
403
404 Then we translate as follows:
405
406         r { op2 = e }
407 ===>
408         let op2 = e in
409         case r of
410           T1 op1 _ op3 -> T1 op1 op2 op3
411           T2 op4 _     -> T2 op4 op2
412           other        -> recUpdError "M.lhs/230"
413
414 It's important that we use the constructor Ids for T1, T2 etc on the
415 RHSs, and do not generate a Core Con directly, because the constructor
416 might do some argument-evaluation first; and may have to throw away some
417 dictionaries.
418
419 \begin{code}
420 dsExpr (RecordUpdOut record_expr dicts rbinds)
421   = dsExpr record_expr   `thenDs` \ record_expr' ->
422
423         -- Desugar the rbinds, and generate let-bindings if
424         -- necessary so that we don't lose sharing
425     dsRbinds rbinds             $ \ rbinds' ->
426     let
427         record_ty               = coreExprType record_expr'
428         (tycon, inst_tys, cons) = _trace "getAppDataTyCon.DsExpr" $ getAppDataTyCon 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 (dataConFieldLabels con `zipEqual` 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 cocon_unit -- unit
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 coreExprType core_d_and_ms)
510                    core_d_and_ms
511     )
512   where
513     dicts_and_methods       = dicts ++ methods
514     dicts_and_methods_exprs = map Var dicts_and_methods
515     num_of_d_and_ms         = length dicts_and_methods
516
517 dsExpr (ClassDictLam dicts methods expr)
518   = dsExpr expr         `thenDs` \ core_expr ->
519     case num_of_d_and_ms of
520         0 -> newSysLocalDs unitTy `thenDs` \ new_x ->
521              returnDs (mkValLam [new_x] core_expr)
522
523         1 -> -- no untupling
524             returnDs (mkValLam dicts_and_methods core_expr)
525
526         _ ->                            -- untuple it
527             newSysLocalDs tuple_ty `thenDs` \ new_x ->
528             returnDs (
529               Lam (ValBinder new_x)
530                 (Case (Var new_x)
531                     (AlgAlts
532                         [(tuple_con, dicts_and_methods, core_expr)]
533                         NoDefault)))
534   where
535     num_of_d_and_ms         = length dicts + length methods
536     dicts_and_methods       = dicts ++ methods
537     tuple_ty                = mkTupleTy    num_of_d_and_ms (map idType dicts_and_methods)
538     tuple_con               = mkTupleCon   num_of_d_and_ms
539
540 #ifdef DEBUG
541 -- HsSyn constructs that just shouldn't be here:
542 dsExpr (HsDo _ _)           = panic "dsExpr:HsDo"
543 dsExpr (ExplicitList _)     = panic "dsExpr:ExplicitList"
544 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
545 dsExpr (ArithSeqIn _)       = panic "dsExpr:ArithSeqIn"
546 #endif
547
548 cocon_unit = mkCon (mkTupleCon 0) [] [] [] -- out here to avoid CAF (sigh)
549 out_of_range_msg                           -- ditto
550   = " out of range: [" ++ show minInt ++ ", " ++ show maxInt ++ "]\n"
551 \end{code}
552
553 %--------------------------------------------------------------------
554
555 @(dsApp e [t_1,..,t_n, e_1,..,e_n])@ returns something with the same
556 value as:
557 \begin{verbatim}
558 e t_1 ... t_n  e_1 .. e_n
559 \end{verbatim}
560
561 We're doing all this so we can saturate constructors (as painlessly as
562 possible).
563
564 \begin{code}
565 type DsCoreArg = GenCoreArg CoreExpr{-NB!-} TyVar UVar
566
567 dsApp :: TypecheckedHsExpr      -- expr to desugar
568       -> [DsCoreArg]            -- accumulated ty/val args: NB:
569       -> DsM CoreExpr   -- final result
570
571 dsApp (HsApp e1 e2) args
572   = dsExpr e2                   `thenDs` \ core_e2 ->
573     dsApp  e1 (VarArg core_e2 : args)
574
575 dsApp (OpApp e1 op e2) args
576   = dsExpr e1                   `thenDs` \ core_e1 ->
577     dsExpr e2                   `thenDs` \ core_e2 ->
578     dsApp  op (VarArg core_e1 : VarArg core_e2 : args)
579
580 dsApp (DictApp expr dicts) args
581   =     -- now, those dicts may have been substituted away...
582     zipWithDs lookupEnvWithDefaultDs dicts (map Var dicts)
583                                 `thenDs` \ core_dicts ->
584     dsApp expr (map VarArg core_dicts ++ args)
585
586 dsApp (TyApp expr tys) args
587   = dsApp expr (map TyArg tys ++ args)
588
589 -- we might should look out for SectionLs, etc., here, but we don't
590
591 dsApp (HsVar v) args
592   = lookupEnvDs v       `thenDs` \ maybe_expr ->
593     case maybe_expr of
594       Just expr -> apply_to_args expr args
595
596       Nothing -> -- we're only saturating constructors and PrimOps
597         case getIdUnfolding v of
598           GenForm _ _ the_unfolding EssentialUnfolding
599             -> do_unfold nullTyVarEnv nullIdEnv (unTagBinders the_unfolding) args
600
601           _ -> apply_to_args (Var v) args
602
603
604 dsApp anything_else args
605   = dsExpr anything_else        `thenDs` \ core_expr ->
606     apply_to_args core_expr args
607
608 -- a DsM version of mkGenApp:
609 apply_to_args :: CoreExpr -> [DsCoreArg] -> DsM CoreExpr
610
611 apply_to_args fun args
612   = let
613         (ty_args, val_args) = foldr sep ([],[]) args
614     in
615     mkAppDs fun ty_args val_args
616   where
617     sep a@(LitArg l)   (tys,vals) = (tys,    (Lit l):vals)
618     sep a@(VarArg e)   (tys,vals) = (tys,    e:vals)
619     sep a@(TyArg ty)   (tys,vals) = (ty:tys, vals)
620     sep a@(UsageArg _) _          = panic "DsExpr:apply_to_args:UsageArg"
621 \end{code}
622
623
624 \begin{code}
625 dsRbinds :: TypecheckedRecordBinds              -- The field bindings supplied
626          -> ([(Id, CoreArg)] -> DsM CoreExpr)   -- A continuation taking the field
627                                                 -- bindings with atomic rhss
628          -> DsM CoreExpr                        -- The result of the continuation,
629                                                 -- wrapped in suitable Lets
630
631 dsRbinds [] continue_with 
632   = continue_with []
633
634 dsRbinds ((sel_id, rhs, pun_flag) : rbinds) continue_with
635   = dsExpr rhs          `thenDs` \ rhs' ->
636     dsExprToAtom rhs'   $ \ rhs_atom ->
637     dsRbinds rbinds     $ \ rbinds' ->
638     continue_with ((sel_id, rhs_atom) : rbinds')
639 \end{code}      
640
641 \begin{code}
642 do_unfold ty_env val_env (Lam (TyBinder tyvar) body) (TyArg ty : args)
643   = do_unfold (addOneToTyVarEnv ty_env tyvar ty) val_env body args
644
645 do_unfold ty_env val_env (Lam (ValBinder binder) body) (VarArg expr : args)
646   = dsExprToAtom expr  $ \ arg_atom ->
647     do_unfold ty_env
648               (addOneToIdEnv val_env binder (argToExpr arg_atom))
649               body args
650
651 do_unfold ty_env val_env body args
652   =     -- Clone the remaining part of the template
653     uniqSMtoDsM (substCoreExpr val_env ty_env body)     `thenDs` \ body' ->
654
655         -- Apply result to remaining arguments
656     apply_to_args body' args
657 \end{code}