[project @ 1996-04-30 17:34:02 by partain]
[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(..)
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
26                         )
27 import Match            ( matchWrapper )
28
29 import CoreUnfold       ( UnfoldingDetails(..), UnfoldingGuidance(..),
30                           FormSummary )
31 import CoreUtils        ( coreExprType, substCoreExpr, argToExpr,
32                           mkCoreIfThenElse, unTagBinders )
33 import CostCentre       ( mkUserCC )
34 import FieldLabel       ( fieldLabelType, FieldLabel )
35 import Id               ( mkTupleCon, idType, nullIdEnv, addOneToIdEnv,
36                           getIdUnfolding, dataConArgTys, dataConFieldLabels,
37                           recordSelectorFieldLabel
38                         )
39 import Literal          ( mkMachInt, Literal(..) )
40 import MagicUFs         ( MagicUnfoldingFun )
41 import PprStyle         ( PprStyle(..) )
42 import PprType          ( GenType )
43 import PrelInfo         ( mkTupleTy, unitTy, nilDataCon, consDataCon,
44                           charDataCon, charTy, rEC_CON_ERROR_ID,
45                           rEC_UPD_ERROR_ID
46                         )
47 import Pretty           ( ppShow, ppBesides, ppPStr, ppStr )
48 import TyCon            ( isDataTyCon, isNewTyCon )
49 import Type             ( splitSigmaTy, splitFunTy, typePrimRep,
50                           getAppDataTyCon, getAppTyCon, applyTy
51                         )
52 import TyVar            ( nullTyVarEnv, addOneToTyVarEnv, GenTyVar{-instance Eq-} )
53 import Usage            ( UVar(..) )
54 import Util             ( zipEqual, pprError, panic, assertPanic )
55
56 maybeBoxedPrimType = panic "DsExpr.maybeBoxedPrimType"
57 splitTyArgs = panic "DsExpr.splitTyArgs"
58
59 mk_nil_con ty = mkCon nilDataCon [] [ty] []  -- micro utility...
60 \end{code}
61
62 The funny business to do with variables is that we look them up in the
63 Id-to-Id and Id-to-Id maps that the monadery is carrying
64 around; if we get hits, we use the value accordingly.
65
66 %************************************************************************
67 %*                                                                      *
68 \subsection[DsExpr-vars-and-cons]{Variables and constructors}
69 %*                                                                      *
70 %************************************************************************
71
72 \begin{code}
73 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
74
75 dsExpr (HsVar var) = dsApp (HsVar var) []
76 \end{code}
77
78 %************************************************************************
79 %*                                                                      *
80 \subsection[DsExpr-literals]{Literals}
81 %*                                                                      *
82 %************************************************************************
83
84 We give int/float literals type Integer and Rational, respectively.
85 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
86 around them.
87
88 ToDo: put in range checks for when converting "i"
89 (or should that be in the typechecker?)
90
91 For numeric literals, we try to detect there use at a standard type
92 (Int, Float, etc.) are directly put in the right constructor.
93 [NB: down with the @App@ conversion.]
94 Otherwise, we punt, putting in a "NoRep" Core literal (where the
95 representation decisions are delayed)...
96
97 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
98
99 \begin{code}
100 dsExpr (HsLitOut (HsString s) _)
101   | _NULL_ s
102   = returnDs (mk_nil_con charTy)
103
104   | _LENGTH_ s == 1
105   = let
106         the_char = mkCon charDataCon [] [] [LitArg (MachChar (_HEAD_ s))]
107         the_nil  = mk_nil_con charTy
108     in
109     mkConDs consDataCon [charTy] [the_char, the_nil]
110
111 -- "_" => build (\ c n -> c 'c' n)      -- LATER
112
113 -- "str" ==> build (\ c n -> foldr charTy T c n "str")
114
115 {- LATER:
116 dsExpr (HsLitOut (HsString str) _)
117   = newTyVarsDs [alphaTyVar]            `thenDs` \ [new_tyvar] ->
118     let
119         new_ty = mkTyVarTy new_tyvar
120     in
121     newSysLocalsDs [
122                 charTy `mkFunTy` (new_ty `mkFunTy` new_ty),
123                 new_ty,
124                        mkForallTy [alphaTyVar]
125                                ((charTy `mkFunTy` (alphaTy `mkFunTy` alphaTy))
126                                         `mkFunTy` (alphaTy `mkFunTy` alphaTy))
127                 ]                       `thenDs` \ [c,n,g] ->
128      returnDs (mkBuild charTy new_tyvar c n g (
129         foldl App
130           (CoTyApp (CoTyApp (Var foldrId) charTy) new_ty) *** ensure non-prim type ***
131           [VarArg c,VarArg n,LitArg (NoRepStr str)]))
132 -}
133
134 -- otherwise, leave it as a NoRepStr;
135 -- the Core-to-STG pass will wrap it in an application of "unpackCStringId".
136
137 dsExpr (HsLitOut (HsString str) _)
138   = returnDs (Lit (NoRepStr str))
139
140 dsExpr (HsLitOut (HsLitLit s) ty)
141   = returnDs ( mkCon data_con [] [] [LitArg (MachLitLit s kind)] )
142   where
143     (data_con, kind)
144       = case (maybeBoxedPrimType ty) of
145           Just (boxing_data_con, prim_ty)
146             -> (boxing_data_con, typePrimRep prim_ty)
147           Nothing
148             -> pprError "ERROR: ``literal-literal'' not a single-constructor type: "
149                         (ppBesides [ppPStr s, ppStr "; type: ", ppr PprDebug ty])
150
151 dsExpr (HsLitOut (HsInt i) _)
152   = returnDs (Lit (NoRepInteger i))
153
154 dsExpr (HsLitOut (HsFrac r) _)
155   = returnDs (Lit (NoRepRational r))
156
157 -- others where we know what to do:
158
159 dsExpr (HsLitOut (HsIntPrim i) _)
160   = if (i >= toInteger minInt && i <= toInteger maxInt) then
161         returnDs (Lit (mkMachInt i))
162     else
163         error ("ERROR: Int constant " ++ show i ++ out_of_range_msg)
164
165 dsExpr (HsLitOut (HsFloatPrim f) _)
166   = returnDs (Lit (MachFloat f))
167     -- ToDo: range checking needed!
168
169 dsExpr (HsLitOut (HsDoublePrim d) _)
170   = returnDs (Lit (MachDouble d))
171     -- ToDo: range checking needed!
172
173 dsExpr (HsLitOut (HsChar c) _)
174   = returnDs ( mkCon charDataCon [] [] [LitArg (MachChar c)] )
175
176 dsExpr (HsLitOut (HsCharPrim c) _)
177   = returnDs (Lit (MachChar c))
178
179 dsExpr (HsLitOut (HsStringPrim s) _)
180   = returnDs (Lit (MachStr s))
181
182 -- end of literals magic. --
183
184 dsExpr expr@(HsLam a_Match)
185   = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
186     returnDs ( mkValLam binders matching_code )
187
188 dsExpr expr@(HsApp e1 e2)    = dsApp expr []
189 dsExpr expr@(OpApp e1 op e2) = dsApp expr []
190 \end{code}
191
192 Operator sections.  At first it looks as if we can convert
193 \begin{verbatim}
194         (expr op)
195 \end{verbatim}
196 to
197 \begin{verbatim}
198         \x -> op expr x
199 \end{verbatim}
200
201 But no!  expr might be a redex, and we can lose laziness badly this
202 way.  Consider
203 \begin{verbatim}
204         map (expr op) xs
205 \end{verbatim}
206 for example.  So we convert instead to
207 \begin{verbatim}
208         let y = expr in \x -> op y x
209 \end{verbatim}
210 If \tr{expr} is actually just a variable, say, then the simplifier
211 will sort it out.
212
213 \begin{code}
214 dsExpr (SectionL expr op)
215   = dsExpr op                   `thenDs` \ core_op ->
216     dsExpr expr                 `thenDs` \ core_expr ->
217     dsExprToAtom core_expr      $ \ y_atom ->
218
219     -- for the type of x, we need the type of op's 2nd argument
220     let
221         x_ty  = case (splitSigmaTy (coreExprType core_op)) of { (_, _, tau_ty) ->
222                 case (splitTyArgs tau_ty)                 of {
223                   ((_:arg2_ty:_), _) -> arg2_ty;
224                   _ -> panic "dsExpr:SectionL:arg 2 ty"
225                 }}
226     in
227     newSysLocalDs x_ty          `thenDs` \ x_id ->
228     returnDs (mkValLam [x_id] (core_op `App` y_atom `App` VarArg x_id)) 
229
230 -- dsExpr (SectionR op expr)    -- \ x -> op x expr
231 dsExpr (SectionR op expr)
232   = dsExpr op                   `thenDs` \ core_op ->
233     dsExpr expr                 `thenDs` \ core_expr ->
234     dsExprToAtom core_expr      $ \ y_atom ->
235
236     -- for the type of x, we need the type of op's 1st argument
237     let
238         x_ty  = case (splitSigmaTy (coreExprType core_op)) of { (_, _, tau_ty) ->
239                 case (splitTyArgs tau_ty)                 of {
240                   ((arg1_ty:_), _) -> arg1_ty;
241                   _ -> panic "dsExpr:SectionR:arg 1 ty"
242                 }}
243     in
244     newSysLocalDs x_ty          `thenDs` \ x_id ->
245     returnDs (mkValLam [x_id] (core_op `App` VarArg x_id `App` y_atom))
246
247 dsExpr (CCall label args may_gc is_asm result_ty)
248   = mapDs dsExpr args           `thenDs` \ core_args ->
249     dsCCall label core_args may_gc is_asm result_ty
250         -- dsCCall does all the unboxification, etc.
251
252 dsExpr (HsSCC cc expr)
253   = dsExpr expr                 `thenDs` \ core_expr ->
254     getModuleAndGroupDs         `thenDs` \ (mod_name, group_name) ->
255     returnDs ( SCC (mkUserCC cc mod_name group_name) core_expr)
256
257 dsExpr expr@(HsCase discrim matches src_loc)
258   = putSrcLocDs src_loc $
259     dsExpr discrim                              `thenDs` \ core_discrim ->
260     matchWrapper CaseMatch matches "case"       `thenDs` \ ([discrim_var], matching_code) ->
261     returnDs ( mkCoLetAny (NonRec discrim_var core_discrim) matching_code )
262
263 dsExpr (ListComp expr quals)
264   = dsExpr expr `thenDs` \ core_expr ->
265     dsListComp core_expr quals
266
267 dsExpr (HsLet binds expr)
268   = dsBinds binds       `thenDs` \ core_binds ->
269     dsExpr expr         `thenDs` \ core_expr ->
270     returnDs ( mkCoLetsAny core_binds core_expr )
271
272 dsExpr (HsDoOut stmts m_id mz_id src_loc)
273   = putSrcLocDs src_loc $
274     panic "dsExpr:HsDoOut"
275
276 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
277   = putSrcLocDs src_loc $
278     dsExpr guard_expr   `thenDs` \ core_guard ->
279     dsExpr then_expr    `thenDs` \ core_then ->
280     dsExpr else_expr    `thenDs` \ core_else ->
281     returnDs (mkCoreIfThenElse core_guard core_then core_else)
282
283 \end{code}
284
285
286 Type lambda and application
287 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
288 \begin{code}
289 dsExpr (TyLam tyvars expr)
290   = dsExpr expr `thenDs` \ core_expr ->
291     returnDs (mkTyLam tyvars core_expr)
292
293 dsExpr expr@(TyApp e tys) = dsApp expr []
294 \end{code}
295
296
297 Various data construction things
298 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
299 \begin{code}
300 dsExpr (ExplicitListOut ty xs)
301   = case xs of
302       []     -> returnDs (mk_nil_con ty)
303       (y:ys) ->
304         dsExpr y                            `thenDs` \ core_hd  ->
305         dsExpr (ExplicitListOut ty ys)  `thenDs` \ core_tl  ->
306         mkConDs consDataCon [ty] [core_hd, core_tl]
307
308 dsExpr (ExplicitTuple expr_list)
309   = mapDs dsExpr expr_list        `thenDs` \ core_exprs  ->
310     mkConDs (mkTupleCon (length expr_list))
311             (map coreExprType core_exprs)
312             core_exprs
313
314 -- Two cases, one for ordinary constructors and one for newtype constructors
315 dsExpr (HsCon con tys args)
316   | isDataTyCon tycon                   -- The usual datatype case
317   = mapDs dsExpr args   `thenDs` \ args_exprs ->
318     mkConDs con tys args_exprs
319
320   | otherwise                           -- The newtype case
321   = ASSERT( isNewTyCon tycon )
322     ASSERT( null rest_args )
323     dsExpr first_arg            `thenDs` \ arg_expr ->
324     returnDs (Coerce (CoerceIn con) result_ty arg_expr)
325
326   where
327     (first_arg:rest_args) = args
328     (args_tys, result_ty) = splitFunTy (foldl applyTy (idType con) tys)
329     (tycon,_)             = getAppTyCon result_ty
330
331 dsExpr (ArithSeqOut expr (From from))
332   = dsExpr expr           `thenDs` \ expr2 ->
333     dsExpr from           `thenDs` \ from2 ->
334     mkAppDs expr2 [] [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 [] [from2, 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 [] [from2, 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 [] [from2, thn2, 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 (arg_tys `zipEqual` dataConFieldLabels con_id) `thenDs` \ con_args ->
388     mkAppDs con_expr' [] 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 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_ty               = coreExprType record_expr'
426         (tycon, inst_tys, cons) = _trace "getAppDataTyCon.DsExpr" $ getAppDataTyCon record_ty
427         cons_to_upd             = filter has_all_fields cons
428
429         -- initial_args are passed to every constructor
430         initial_args            = map TyArg inst_tys ++ map VarArg dicts
431                 
432         mk_val_arg (field, arg_id) 
433           = case [arg | (f, arg) <- rbinds',
434                         field == recordSelectorFieldLabel f] of
435               (arg:args) -> ASSERT(null args)
436                             arg
437               []         -> VarArg arg_id
438
439         mk_alt con
440           = newSysLocalsDs (dataConArgTys con inst_tys) `thenDs` \ arg_ids ->
441             let 
442                 val_args = map mk_val_arg (dataConFieldLabels con `zipEqual` arg_ids)
443             in
444             returnDs (con, arg_ids, mkGenApp (mkGenApp (Var con) initial_args) val_args)
445
446         mk_default
447           | length cons_to_upd == length cons 
448           = returnDs NoDefault
449           | otherwise                       
450           = newSysLocalDs record_ty                     `thenDs` \ deflt_id ->
451             mkErrorAppDs rEC_UPD_ERROR_ID record_ty ""  `thenDs` \ err ->
452             returnDs (BindDefault deflt_id err)
453     in
454     mapDs mk_alt cons_to_upd    `thenDs` \ alts ->
455     mk_default                  `thenDs` \ deflt ->
456
457     returnDs (Case record_expr' (AlgAlts alts deflt))
458
459   where
460     has_all_fields :: Id -> Bool
461     has_all_fields con_id 
462       = all ok rbinds
463       where
464         con_fields        = dataConFieldLabels con_id
465         ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
466 \end{code}
467
468 Dictionary lambda and application
469 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
470 @DictLam@ and @DictApp@ turn into the regular old things.
471 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
472 complicated; reminiscent of fully-applied constructors.
473 \begin{code}
474 dsExpr (DictLam dictvars expr)
475   = dsExpr expr `thenDs` \ core_expr ->
476     returnDs( mkValLam dictvars core_expr )
477
478 ------------------
479
480 dsExpr expr@(DictApp e dicts)   -- becomes a curried application
481   = dsApp expr []
482 \end{code}
483
484 @SingleDicts@ become @Locals@; @Dicts@ turn into tuples, unless
485 of length 0 or 1.
486 @ClassDictLam dictvars methods expr@ is ``the opposite'':
487 \begin{verbatim}
488 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
489 \end{verbatim}
490 \begin{code}
491 dsExpr (SingleDict dict)        -- just a local
492   = lookupEnvWithDefaultDs dict (Var dict)
493
494 dsExpr (Dictionary dicts methods)
495   = -- hey, these things may have been substituted away...
496     zipWithDs lookupEnvWithDefaultDs
497               dicts_and_methods dicts_and_methods_exprs
498                         `thenDs` \ core_d_and_ms ->
499
500     (case num_of_d_and_ms of
501       0 -> returnDs cocon_unit -- unit
502
503       1 -> returnDs (head core_d_and_ms) -- just a single Id
504
505       _ ->          -- tuple 'em up
506            mkConDs (mkTupleCon num_of_d_and_ms)
507                    (map coreExprType core_d_and_ms)
508                    core_d_and_ms
509     )
510   where
511     dicts_and_methods       = dicts ++ methods
512     dicts_and_methods_exprs = map Var dicts_and_methods
513     num_of_d_and_ms         = length dicts_and_methods
514
515 dsExpr (ClassDictLam dicts methods expr)
516   = dsExpr expr         `thenDs` \ core_expr ->
517     case num_of_d_and_ms of
518         0 -> newSysLocalDs unitTy `thenDs` \ new_x ->
519              returnDs (mkValLam [new_x] core_expr)
520
521         1 -> -- no untupling
522             returnDs (mkValLam dicts_and_methods core_expr)
523
524         _ ->                            -- untuple it
525             newSysLocalDs tuple_ty `thenDs` \ new_x ->
526             returnDs (
527               Lam (ValBinder new_x)
528                 (Case (Var new_x)
529                     (AlgAlts
530                         [(tuple_con, dicts_and_methods, core_expr)]
531                         NoDefault)))
532   where
533     num_of_d_and_ms         = length dicts + length methods
534     dicts_and_methods       = dicts ++ methods
535     tuple_ty                = mkTupleTy    num_of_d_and_ms (map idType dicts_and_methods)
536     tuple_con               = mkTupleCon   num_of_d_and_ms
537
538 #ifdef DEBUG
539 -- HsSyn constructs that just shouldn't be here:
540 dsExpr (HsDo _ _)           = panic "dsExpr:HsDo"
541 dsExpr (ExplicitList _)     = panic "dsExpr:ExplicitList"
542 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
543 dsExpr (ArithSeqIn _)       = panic "dsExpr:ArithSeqIn"
544 #endif
545
546 cocon_unit = mkCon (mkTupleCon 0) [] [] [] -- out here to avoid CAF (sigh)
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 type DsCoreArg = GenCoreArg CoreExpr{-NB!-} TyVar UVar
564
565 dsApp :: TypecheckedHsExpr      -- expr to desugar
566       -> [DsCoreArg]            -- accumulated ty/val args: NB:
567       -> DsM CoreExpr   -- final result
568
569 dsApp (HsApp e1 e2) args
570   = dsExpr e2                   `thenDs` \ core_e2 ->
571     dsApp  e1 (VarArg core_e2 : args)
572
573 dsApp (OpApp e1 op e2) args
574   = dsExpr e1                   `thenDs` \ core_e1 ->
575     dsExpr e2                   `thenDs` \ core_e2 ->
576     dsApp  op (VarArg core_e1 : VarArg core_e2 : args)
577
578 dsApp (DictApp expr dicts) args
579   =     -- now, those dicts may have been substituted away...
580     zipWithDs lookupEnvWithDefaultDs dicts (map Var dicts)
581                                 `thenDs` \ core_dicts ->
582     dsApp expr (map VarArg core_dicts ++ args)
583
584 dsApp (TyApp expr tys) args
585   = dsApp expr (map TyArg tys ++ args)
586
587 -- we might should look out for SectionLs, etc., here, but we don't
588
589 dsApp (HsVar v) args
590   = lookupEnvDs v       `thenDs` \ maybe_expr ->
591     case maybe_expr of
592       Just expr -> apply_to_args expr args
593
594       Nothing -> -- we're only saturating constructors and PrimOps
595         case getIdUnfolding v of
596           GenForm _ _ the_unfolding EssentialUnfolding
597             -> do_unfold nullTyVarEnv nullIdEnv (unTagBinders the_unfolding) args
598
599           _ -> apply_to_args (Var v) args
600
601
602 dsApp anything_else args
603   = dsExpr anything_else        `thenDs` \ core_expr ->
604     apply_to_args core_expr args
605
606 -- a DsM version of mkGenApp:
607 apply_to_args :: CoreExpr -> [DsCoreArg] -> DsM CoreExpr
608
609 apply_to_args fun args
610   = let
611         (ty_args, val_args) = foldr sep ([],[]) args
612     in
613     mkAppDs fun ty_args val_args
614   where
615     sep a@(LitArg l)   (tys,vals) = (tys,    (Lit l):vals)
616     sep a@(VarArg e)   (tys,vals) = (tys,    e:vals)
617     sep a@(TyArg ty)   (tys,vals) = (ty:tys, vals)
618     sep a@(UsageArg _) _          = panic "DsExpr:apply_to_args:UsageArg"
619 \end{code}
620
621
622 \begin{code}
623 dsRbinds :: TypecheckedRecordBinds              -- The field bindings supplied
624          -> ([(Id, CoreArg)] -> DsM CoreExpr)   -- A continuation taking the field
625                                                 -- bindings with atomic rhss
626          -> DsM CoreExpr                        -- The result of the continuation,
627                                                 -- wrapped in suitable Lets
628
629 dsRbinds [] continue_with 
630   = continue_with []
631
632 dsRbinds ((sel_id, rhs, pun_flag) : rbinds) continue_with
633   = dsExpr rhs          `thenDs` \ rhs' ->
634     dsExprToAtom rhs'   $ \ rhs_atom ->
635     dsRbinds rbinds     $ \ rbinds' ->
636     continue_with ((sel_id, rhs_atom) : rbinds')
637 \end{code}      
638
639 \begin{code}
640 do_unfold ty_env val_env (Lam (TyBinder tyvar) body) (TyArg ty : args)
641   = do_unfold (addOneToTyVarEnv ty_env tyvar ty) val_env body args
642
643 do_unfold ty_env val_env (Lam (ValBinder binder) body) (VarArg expr : args)
644   = dsExprToAtom expr  $ \ arg_atom ->
645     do_unfold ty_env
646               (addOneToIdEnv val_env binder (argToExpr arg_atom))
647               body args
648
649 do_unfold ty_env val_env body args
650   =     -- Clone the remaining part of the template
651     uniqSMtoDsM (substCoreExpr val_env ty_env body)     `thenDs` \ body' ->
652
653         -- Apply result to remaining arguments
654     apply_to_args body' args
655 \end{code}