[project @ 1999-06-17 09:51:16 by simonmar]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsExpr.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[DsExpr]{Matching expressions (Exprs)}
5
6 \begin{code}
7 module DsExpr ( dsExpr, dsLet ) where
8
9 #include "HsVersions.h"
10
11
12 import HsSyn            ( failureFreePat,
13                           HsExpr(..), OutPat(..), HsLit(..), ArithSeqInfo(..),
14                           Stmt(..), StmtCtxt(..), Match(..), HsBinds(..), MonoBinds(..), 
15                           mkSimpleMatch
16                         )
17 import TcHsSyn          ( TypecheckedHsExpr, TypecheckedHsBinds,
18                           TypecheckedStmt,
19                           maybeBoxedPrimType
20
21                         )
22 import CoreSyn
23
24 import DsMonad
25 import DsBinds          ( dsMonoBinds, AutoScc(..) )
26 import DsGRHSs          ( dsGuarded )
27 import DsCCall          ( dsCCall )
28 import DsListComp       ( dsListComp )
29 import DsUtils          ( mkErrorAppDs, mkDsLets, mkConsExpr, mkNilExpr )
30 import Match            ( matchWrapper, matchSimply )
31
32 import CoreUtils        ( coreExprType )
33 import CostCentre       ( mkUserCC )
34 import FieldLabel       ( FieldLabel )
35 import Id               ( Id, idType, recordSelectorFieldLabel )
36 import Const            ( Con(..) )
37 import DataCon          ( DataCon, dataConId, dataConTyCon, dataConArgTys, dataConFieldLabels )
38 import Const            ( mkMachInt, Literal(..), mkStrLit )
39 import PrelInfo         ( rEC_CON_ERROR_ID, rEC_UPD_ERROR_ID, iRREFUT_PAT_ERROR_ID )
40 import TyCon            ( isNewTyCon )
41 import DataCon          ( isExistentialDataCon )
42 import Type             ( splitFunTys, mkTyConApp,
43                           splitAlgTyConApp, splitTyConApp_maybe, isNotUsgTy, unUsgTy,
44                           splitAppTy, isUnLiftedType, Type
45                         )
46 import TysWiredIn       ( tupleCon, unboxedTupleCon,
47                           listTyCon, mkListTy,
48                           charDataCon, charTy, stringTy
49                         )
50 import BasicTypes       ( RecFlag(..) )
51 import Maybes           ( maybeToBool )
52 import Util             ( zipEqual, zipWithEqual )
53 import Outputable
54 \end{code}
55
56
57 %************************************************************************
58 %*                                                                      *
59 \subsection{dsLet}
60 %*                                                                      *
61 %************************************************************************
62
63 @dsLet@ is a match-result transformer, taking the @MatchResult@ for the body
64 and transforming it into one for the let-bindings enclosing the body.
65
66 This may seem a bit odd, but (source) let bindings can contain unboxed
67 binds like
68 \begin{verbatim}
69         C x# = e
70 \end{verbatim}
71 This must be transformed to a case expression and, if the type has
72 more than one constructor, may fail.
73
74 \begin{code}
75 dsLet :: TypecheckedHsBinds -> CoreExpr -> DsM CoreExpr
76
77 dsLet EmptyBinds body
78   = returnDs body
79
80 dsLet (ThenBinds b1 b2) body
81   = dsLet b2 body       `thenDs` \ body' ->
82     dsLet b1 body'
83   
84 -- Special case for bindings which bind unlifted variables
85 -- Silently ignore INLINE pragmas...
86 dsLet (MonoBind (AbsBinds [] [] binder_triples inlines
87                           (PatMonoBind pat grhss loc)) sigs is_rec) body
88   | or [isUnLiftedType (idType g) | (_, g, l) <- binder_triples]
89   = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
90     putSrcLocDs loc                     $
91     dsGuarded grhss                     `thenDs` \ rhs ->
92     let
93         body' = foldr bind body binder_triples
94         bind (tyvars, g, l) body = ASSERT( null tyvars )
95                                    bindNonRec g (Var l) body
96     in
97     mkErrorAppDs iRREFUT_PAT_ERROR_ID result_ty (showSDoc (ppr pat))
98     `thenDs` \ error_expr ->
99     matchSimply rhs PatBindMatch pat body' error_expr
100   where
101     result_ty = coreExprType body
102
103 -- Ordinary case for bindings
104 dsLet (MonoBind binds sigs is_rec) body
105   = dsMonoBinds NoSccs binds []  `thenDs` \ prs ->
106     case is_rec of
107       Recursive    -> returnDs (Let (Rec prs) body)
108       NonRecursive -> returnDs (mkDsLets [NonRec b r | (b,r) <- prs] body)
109 \end{code}
110
111 %************************************************************************
112 %*                                                                      *
113 \subsection[DsExpr-vars-and-cons]{Variables and constructors}
114 %*                                                                      *
115 %************************************************************************
116
117 \begin{code}
118 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
119
120 dsExpr e@(HsVar var) = returnDs (Var var)
121 \end{code}
122
123 %************************************************************************
124 %*                                                                      *
125 \subsection[DsExpr-literals]{Literals}
126 %*                                                                      *
127 %************************************************************************
128
129 We give int/float literals type @Integer@ and @Rational@, respectively.
130 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
131 around them.
132
133 ToDo: put in range checks for when converting ``@i@''
134 (or should that be in the typechecker?)
135
136 For numeric literals, we try to detect there use at a standard type
137 (@Int@, @Float@, etc.) are directly put in the right constructor.
138 [NB: down with the @App@ conversion.]
139 Otherwise, we punt, putting in a @NoRep@ Core literal (where the
140 representation decisions are delayed)...
141
142 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
143
144 \begin{code}
145 dsExpr (HsLitOut (HsString s) _)
146   | _NULL_ s
147   = returnDs (mkNilExpr charTy)
148
149   | _LENGTH_ s == 1
150   = let
151         the_char = mkConApp charDataCon [mkLit (MachChar (_HEAD_ s))]
152         the_nil  = mkNilExpr charTy
153         the_cons = mkConsExpr charTy the_char the_nil
154     in
155     returnDs the_cons
156
157
158 -- "_" => build (\ c n -> c 'c' n)      -- LATER
159
160 -- "str" ==> build (\ c n -> foldr charTy T c n "str")
161
162 {- LATER:
163 dsExpr (HsLitOut (HsString str) _)
164   = newTyVarsDs [alphaTyVar]            `thenDs` \ [new_tyvar] ->
165     let
166         new_ty = mkTyVarTy new_tyvar
167     in
168     newSysLocalsDs [
169                 charTy `mkFunTy` (new_ty `mkFunTy` new_ty),
170                 new_ty,
171                        mkForallTy [alphaTyVar]
172                                ((charTy `mkFunTy` (alphaTy `mkFunTy` alphaTy))
173                                         `mkFunTy` (alphaTy `mkFunTy` alphaTy))
174                 ]                       `thenDs` \ [c,n,g] ->
175      returnDs (mkBuild charTy new_tyvar c n g (
176         foldl App
177           (CoTyApp (CoTyApp (Var foldrId) charTy) new_ty) *** ensure non-prim type ***
178           [VarArg c,VarArg n,LitArg (NoRepStr str)]))
179 -}
180
181 -- otherwise, leave it as a NoRepStr;
182 -- the Core-to-STG pass will wrap it in an application of "unpackCStringId".
183
184 dsExpr (HsLitOut (HsString str) _)
185   = returnDs (mkLit (NoRepStr str stringTy))
186
187 dsExpr (HsLitOut (HsLitLit str) ty)
188   | isUnLiftedType ty
189   = returnDs (mkLit (MachLitLit str ty))
190   | otherwise
191   = case (maybeBoxedPrimType ty) of
192       Just (boxing_data_con, prim_ty) ->
193             returnDs ( mkConApp boxing_data_con [mkLit (MachLitLit str prim_ty)] )
194       _ -> 
195         pprError "ERROR:"
196                  (vcat
197                    [ hcat [ text "Cannot see data constructor of ``literal-literal''s type: "
198                          , text "value:", quotes (quotes (ptext str))
199                          , text "; type: ", ppr ty
200                          ]
201                    , text "Try compiling with -fno-prune-tydecls."
202                    ])
203                   
204   where
205     (data_con, prim_ty)
206       = case (maybeBoxedPrimType ty) of
207           Just (boxing_data_con, prim_ty) -> (boxing_data_con, prim_ty)
208           Nothing
209             -> pprPanic "ERROR: ``literal-literal'' not a single-constructor type: "
210                         (hcat [ptext str, text "; type: ", ppr ty])
211
212 dsExpr (HsLitOut (HsInt i) ty)
213   = returnDs (mkLit (NoRepInteger i ty))
214
215 dsExpr (HsLitOut (HsFrac r) ty)
216   = returnDs (mkLit (NoRepRational r ty))
217
218 -- others where we know what to do:
219
220 dsExpr (HsLitOut (HsIntPrim i) _)
221   | (i >= toInteger minInt && i <= toInteger maxInt) 
222   = returnDs (mkLit (mkMachInt i))
223   | otherwise
224   = error ("ERROR: Int constant " ++ show i ++ out_of_range_msg)
225
226 dsExpr (HsLitOut (HsFloatPrim f) _)
227   = returnDs (mkLit (MachFloat f))
228     -- ToDo: range checking needed!
229
230 dsExpr (HsLitOut (HsDoublePrim d) _)
231   = returnDs (mkLit (MachDouble d))
232     -- ToDo: range checking needed!
233
234 dsExpr (HsLitOut (HsChar c) _)
235   = returnDs ( mkConApp charDataCon [mkLit (MachChar c)] )
236
237 dsExpr (HsLitOut (HsCharPrim c) _)
238   = returnDs (mkLit (MachChar c))
239
240 dsExpr (HsLitOut (HsStringPrim s) _)
241   = returnDs (mkLit (MachStr s))
242
243 -- end of literals magic. --
244
245 dsExpr expr@(HsLam a_Match)
246   = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
247     returnDs (mkLams binders matching_code)
248
249 dsExpr expr@(HsApp fun arg)      
250   = dsExpr fun          `thenDs` \ core_fun ->
251     dsExpr arg          `thenDs` \ core_arg ->
252     returnDs (core_fun `App` core_arg)
253
254 \end{code}
255
256 Operator sections.  At first it looks as if we can convert
257 \begin{verbatim}
258         (expr op)
259 \end{verbatim}
260 to
261 \begin{verbatim}
262         \x -> op expr x
263 \end{verbatim}
264
265 But no!  expr might be a redex, and we can lose laziness badly this
266 way.  Consider
267 \begin{verbatim}
268         map (expr op) xs
269 \end{verbatim}
270 for example.  So we convert instead to
271 \begin{verbatim}
272         let y = expr in \x -> op y x
273 \end{verbatim}
274 If \tr{expr} is actually just a variable, say, then the simplifier
275 will sort it out.
276
277 \begin{code}
278 dsExpr (OpApp e1 op _ e2)
279   = dsExpr op                                           `thenDs` \ core_op ->
280     -- for the type of y, we need the type of op's 2nd argument
281     dsExpr e1                           `thenDs` \ x_core ->
282     dsExpr e2                           `thenDs` \ y_core ->
283     returnDs (mkApps core_op [x_core, y_core])
284     
285 dsExpr (SectionL expr op)
286   = dsExpr op                                           `thenDs` \ core_op ->
287     -- for the type of y, we need the type of op's 2nd argument
288     let
289         (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
290     in
291     dsExpr expr                         `thenDs` \ x_core ->
292     newSysLocalDs x_ty                  `thenDs` \ x_id ->
293     newSysLocalDs y_ty                  `thenDs` \ y_id ->
294
295     returnDs (bindNonRec x_id x_core $
296               Lam y_id (mkApps core_op [Var x_id, Var y_id]))
297
298 -- dsExpr (SectionR op expr)    -- \ x -> op x expr
299 dsExpr (SectionR op expr)
300   = dsExpr op                   `thenDs` \ core_op ->
301     -- for the type of x, we need the type of op's 2nd argument
302     let
303         (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
304     in
305     dsExpr expr                         `thenDs` \ y_core ->
306     newSysLocalDs x_ty                  `thenDs` \ x_id ->
307     newSysLocalDs y_ty                  `thenDs` \ y_id ->
308
309     returnDs (bindNonRec y_id y_core $
310               Lam x_id (mkApps core_op [Var x_id, Var y_id]))
311
312 dsExpr (CCall label args may_gc is_asm result_ty)
313   = mapDs dsExpr args           `thenDs` \ core_args ->
314     dsCCall label core_args may_gc is_asm result_ty
315         -- dsCCall does all the unboxification, etc.
316
317 dsExpr (HsSCC cc expr)
318   = dsExpr expr                 `thenDs` \ core_expr ->
319     getModuleAndGroupDs         `thenDs` \ (mod_name, group_name) ->
320     returnDs (Note (SCC (mkUserCC cc mod_name group_name)) core_expr)
321
322 -- special case to handle unboxed tuple patterns.
323
324 dsExpr (HsCase discrim matches@[Match _ [TuplePat ps boxed] _ _] src_loc)
325  | not boxed && all var_pat ps 
326  =  putSrcLocDs src_loc $
327     dsExpr discrim                        `thenDs` \ core_discrim ->
328     matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
329     case matching_code of
330         Case (Var x) bndr alts | x == discrim_var -> 
331                 returnDs (Case core_discrim bndr alts)
332         _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
333
334 dsExpr (HsCase discrim matches src_loc)
335   = putSrcLocDs src_loc $
336     dsExpr discrim                        `thenDs` \ core_discrim ->
337     matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
338     returnDs (bindNonRec discrim_var core_discrim matching_code)
339
340 dsExpr (HsLet binds body)
341   = dsExpr body         `thenDs` \ body' ->
342     dsLet binds body'
343     
344 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
345   | maybeToBool maybe_list_comp
346   =     -- Special case for list comprehensions
347     putSrcLocDs src_loc $
348     dsListComp stmts elt_ty
349
350   | otherwise
351   = putSrcLocDs src_loc $
352     dsDo do_or_lc stmts return_id then_id fail_id result_ty
353   where
354     maybe_list_comp 
355         = case (do_or_lc, splitTyConApp_maybe result_ty) of
356             (ListComp, Just (tycon, [elt_ty]))
357                   | tycon == listTyCon
358                  -> Just elt_ty
359             other -> Nothing
360         -- We need the ListComp form to use deListComp (rather than the "do" form)
361         -- because the "return" in a do block is a call to "PrelBase.return", and
362         -- not a ReturnStmt.  Only the ListComp form has ReturnStmts
363
364     Just elt_ty = maybe_list_comp
365
366 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
367   = putSrcLocDs src_loc $
368     dsExpr guard_expr   `thenDs` \ core_guard ->
369     dsExpr then_expr    `thenDs` \ core_then ->
370     dsExpr else_expr    `thenDs` \ core_else ->
371     returnDs (mkIfThenElse core_guard core_then core_else)
372 \end{code}
373
374
375 \noindent
376 \underline{\bf Type lambda and application}
377 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~
378 \begin{code}
379 dsExpr (TyLam tyvars expr)
380   = dsExpr expr `thenDs` \ core_expr ->
381     returnDs (mkLams tyvars core_expr)
382
383 dsExpr (TyApp expr tys)
384   = dsExpr expr         `thenDs` \ core_expr ->
385     returnDs (mkTyApps core_expr tys)
386 \end{code}
387
388
389 \noindent
390 \underline{\bf Various data construction things}
391 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
392 \begin{code}
393 dsExpr (ExplicitListOut ty xs)
394   = go xs
395   where
396     list_ty   = mkListTy ty
397
398     go []     = returnDs (mkNilExpr ty)
399     go (x:xs) = dsExpr x                                `thenDs` \ core_x ->
400                 go xs                                   `thenDs` \ core_xs ->
401                 ASSERT( isNotUsgTy ty )
402                 returnDs (mkConsExpr ty core_x core_xs)
403
404 dsExpr (ExplicitTuple expr_list boxed)
405   = mapDs dsExpr expr_list        `thenDs` \ core_exprs  ->
406     returnDs (mkConApp ((if boxed 
407                             then tupleCon 
408                             else unboxedTupleCon) (length expr_list))
409                 (map (Type . unUsgTy . coreExprType) core_exprs ++ core_exprs))
410                 -- the above unUsgTy is *required* -- KSW 1999-04-07
411
412 dsExpr (HsCon con_id [ty] [arg])
413   | isNewTyCon tycon
414   = dsExpr arg               `thenDs` \ arg' ->
415     returnDs (Note (Coerce result_ty (unUsgTy (coreExprType arg'))) arg')
416   where
417     result_ty = mkTyConApp tycon [ty]
418     tycon     = dataConTyCon con_id
419
420 dsExpr (HsCon con_id tys args)
421   = mapDs dsExpr args             `thenDs` \ args2  ->
422     ASSERT( all isNotUsgTy tys )
423     returnDs (mkConApp con_id (map Type tys ++ args2))
424
425 dsExpr (ArithSeqOut expr (From from))
426   = dsExpr expr           `thenDs` \ expr2 ->
427     dsExpr from           `thenDs` \ from2 ->
428     returnDs (App expr2 from2)
429
430 dsExpr (ArithSeqOut expr (FromTo from two))
431   = dsExpr expr           `thenDs` \ expr2 ->
432     dsExpr from           `thenDs` \ from2 ->
433     dsExpr two            `thenDs` \ two2 ->
434     returnDs (mkApps expr2 [from2, two2])
435
436 dsExpr (ArithSeqOut expr (FromThen from thn))
437   = dsExpr expr           `thenDs` \ expr2 ->
438     dsExpr from           `thenDs` \ from2 ->
439     dsExpr thn            `thenDs` \ thn2 ->
440     returnDs (mkApps expr2 [from2, thn2])
441
442 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
443   = dsExpr expr           `thenDs` \ expr2 ->
444     dsExpr from           `thenDs` \ from2 ->
445     dsExpr thn            `thenDs` \ thn2 ->
446     dsExpr two            `thenDs` \ two2 ->
447     returnDs (mkApps expr2 [from2, thn2, two2])
448 \end{code}
449
450 \noindent
451 \underline{\bf Record construction and update}
452 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
453 For record construction we do this (assuming T has three arguments)
454 \begin{verbatim}
455         T { op2 = e }
456 ==>
457         let err = /\a -> recConErr a 
458         T (recConErr t1 "M.lhs/230/op1") 
459           e 
460           (recConErr t1 "M.lhs/230/op3")
461 \end{verbatim}
462 @recConErr@ then converts its arugment string into a proper message
463 before printing it as
464 \begin{verbatim}
465         M.lhs, line 230: missing field op1 was evaluated
466 \end{verbatim}
467
468 We also handle @C{}@ as valid construction syntax for an unlabelled
469 constructor @C@, setting all of @C@'s fields to bottom.
470
471 \begin{code}
472 dsExpr (RecordConOut data_con con_expr rbinds)
473   = dsExpr con_expr     `thenDs` \ con_expr' ->
474     let
475         (arg_tys, _) = splitFunTys (coreExprType con_expr')
476
477         mk_arg (arg_ty, lbl)
478           = case [rhs | (sel_id,rhs,_) <- rbinds,
479                         lbl == recordSelectorFieldLabel sel_id] of
480               (rhs:rhss) -> ASSERT( null rhss )
481                             dsExpr rhs
482               []         -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
483         unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
484
485         labels = dataConFieldLabels data_con
486     in
487
488     (if null labels
489         then mapDs unlabelled_bottom arg_tys
490         else mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
491         `thenDs` \ con_args ->
492
493     returnDs (mkApps con_expr' con_args)
494 \end{code}
495
496 Record update is a little harder. Suppose we have the decl:
497 \begin{verbatim}
498         data T = T1 {op1, op2, op3 :: Int}
499                | T2 {op4, op2 :: Int}
500                | T3
501 \end{verbatim}
502 Then we translate as follows:
503 \begin{verbatim}
504         r { op2 = e }
505 ===>
506         let op2 = e in
507         case r of
508           T1 op1 _ op3 -> T1 op1 op2 op3
509           T2 op4 _     -> T2 op4 op2
510           other        -> recUpdError "M.lhs/230"
511 \end{verbatim}
512 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
513 RHSs, and do not generate a Core @Con@ directly, because the constructor
514 might do some argument-evaluation first; and may have to throw away some
515 dictionaries.
516
517 \begin{code}
518 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
519   = dsExpr record_expr          `thenDs` \ record_expr' ->
520
521         -- Desugar the rbinds, and generate let-bindings if
522         -- necessary so that we don't lose sharing
523
524     let
525         ds_rbind (sel_id, rhs, pun_flag)
526           = dsExpr rhs                          `thenDs` \ rhs' ->
527             returnDs (recordSelectorFieldLabel sel_id, rhs')
528     in
529     mapDs ds_rbind rbinds                       `thenDs` \ rbinds' ->
530     let
531         record_in_ty               = coreExprType record_expr'
532         (tycon, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
533         (_,     out_inst_tys, _)   = splitAlgTyConApp record_out_ty
534         cons_to_upd                = filter has_all_fields cons
535
536         -- initial_args are passed to every constructor
537         initial_args            = map Type out_inst_tys ++ map Var dicts
538                 
539         mk_val_arg field old_arg_id 
540           = case [rhs | (f, rhs) <- rbinds', field == f] of
541               (rhs:rest) -> ASSERT(null rest) rhs
542               []         -> Var old_arg_id
543
544         mk_alt con
545           = newSysLocalsDs (dataConArgTys con in_inst_tys)      `thenDs` \ arg_ids ->
546             let 
547                 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
548                                         (dataConFieldLabels con) arg_ids
549                 rhs = mkApps (mkApps (Var (dataConId con)) initial_args) val_args
550             in
551             returnDs (DataCon con, arg_ids, rhs)
552
553         mk_default
554           | length cons_to_upd == length cons 
555           = returnDs []
556           | otherwise                       
557           = mkErrorAppDs rEC_UPD_ERROR_ID record_out_ty ""      `thenDs` \ err ->
558             returnDs [(DEFAULT, [], err)]
559     in
560         -- Record stuff doesn't work for existentials
561     ASSERT( all (not . isExistentialDataCon) cons )
562
563     newSysLocalDs record_in_ty  `thenDs` \ case_bndr ->
564     mapDs mk_alt cons_to_upd    `thenDs` \ alts ->
565     mk_default                  `thenDs` \ deflt ->
566
567     returnDs (Case record_expr' case_bndr (alts ++ deflt))
568   where
569     has_all_fields :: DataCon -> Bool
570     has_all_fields con_id 
571       = all ok rbinds
572       where
573         con_fields        = dataConFieldLabels con_id
574         ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
575 \end{code}
576
577
578 \noindent
579 \underline{\bf Dictionary lambda and application}
580 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
581 @DictLam@ and @DictApp@ turn into the regular old things.
582 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
583 complicated; reminiscent of fully-applied constructors.
584 \begin{code}
585 dsExpr (DictLam dictvars expr)
586   = dsExpr expr `thenDs` \ core_expr ->
587     returnDs (mkLams dictvars core_expr)
588
589 ------------------
590
591 dsExpr (DictApp expr dicts)     -- becomes a curried application
592   = dsExpr expr                 `thenDs` \ core_expr ->
593     returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
594 \end{code}
595
596 \begin{code}
597
598 #ifdef DEBUG
599 -- HsSyn constructs that just shouldn't be here:
600 dsExpr (HsDo _ _ _)         = panic "dsExpr:HsDo"
601 dsExpr (ExplicitList _)     = panic "dsExpr:ExplicitList"
602 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
603 dsExpr (ArithSeqIn _)       = panic "dsExpr:ArithSeqIn"
604 #endif
605
606 out_of_range_msg                           -- ditto
607   = " out of range: [" ++ show minInt ++ ", " ++ show maxInt ++ "]\n"
608 \end{code}
609
610 %--------------------------------------------------------------------
611
612 Basically does the translation given in the Haskell~1.3 report:
613
614 \begin{code}
615 dsDo    :: StmtCtxt
616         -> [TypecheckedStmt]
617         -> Id           -- id for: return m
618         -> Id           -- id for: (>>=) m
619         -> Id           -- id for: fail m
620         -> Type         -- Element type; the whole expression has type (m t)
621         -> DsM CoreExpr
622
623 dsDo do_or_lc stmts return_id then_id fail_id result_ty
624   = let
625         (_, b_ty) = splitAppTy result_ty        -- result_ty must be of the form (m b)
626         
627         go [ReturnStmt expr] 
628           = dsExpr expr                 `thenDs` \ expr2 ->
629             returnDs (mkApps (Var return_id) [Type b_ty, expr2])
630     
631         go (GuardStmt expr locn : stmts)
632           = do_expr expr locn                   `thenDs` \ expr2 ->
633             go stmts                            `thenDs` \ rest ->
634             let msg = ASSERT( isNotUsgTy b_ty )
635                  "Pattern match failure in do expression, " ++ showSDoc (ppr locn) in
636             returnDs (mkIfThenElse expr2 
637                                    rest 
638                                    (App (App (Var fail_id) 
639                                              (Type b_ty))
640                                              (mkLit (mkStrLit msg stringTy))))
641     
642         go (ExprStmt expr locn : stmts)
643           = do_expr expr locn           `thenDs` \ expr2 ->
644             let
645                 (_, a_ty) = splitAppTy (coreExprType expr2)  -- Must be of form (m a)
646             in
647             if null stmts then
648                 returnDs expr2
649             else
650                 go stmts                `thenDs` \ rest  ->
651                 newSysLocalDs a_ty              `thenDs` \ ignored_result_id ->
652                 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2, 
653                                                 Lam ignored_result_id rest])
654     
655         go (LetStmt binds : stmts )
656           = go stmts            `thenDs` \ rest   ->
657             dsLet binds rest
658             
659         go (BindStmt pat expr locn : stmts)
660           = putSrcLocDs locn $
661             dsExpr expr            `thenDs` \ expr2 ->
662             let
663                 (_, a_ty)  = splitAppTy (coreExprType expr2) -- Must be of form (m a)
664                 fail_expr  = HsApp (TyApp (HsVar fail_id) [b_ty])
665                                    (HsLitOut (HsString (_PK_ msg)) stringTy)
666                 msg = ASSERT2( isNotUsgTy a_ty, ppr a_ty )
667                       ASSERT2( isNotUsgTy b_ty, ppr b_ty )
668                       "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
669                 main_match = mkSimpleMatch [pat] 
670                                            (HsDoOut do_or_lc stmts return_id then_id
671                                                     fail_id result_ty locn)
672                                            (Just result_ty) locn
673                 the_matches
674                   | failureFreePat pat = [main_match]
675                   | otherwise          =
676                       [ main_match
677                       , mkSimpleMatch [WildPat a_ty] fail_expr (Just result_ty) locn
678                       ]
679             in
680             matchWrapper DoBindMatch the_matches match_msg
681                                 `thenDs` \ (binders, matching_code) ->
682             returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
683                                             mkLams binders matching_code])
684     in
685     go stmts
686
687   where
688     do_expr expr locn = putSrcLocDs locn (dsExpr expr)
689
690     match_msg = case do_or_lc of
691                         DoStmt   -> "`do' statement"
692                         ListComp -> "comprehension"
693 \end{code}
694
695 \begin{code}
696 var_pat (WildPat _) = True
697 var_pat (VarPat _) = True
698 var_pat _ = False
699 \end{code}
700