[project @ 2005-05-19 11:15:40 by simonpj]
[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, dsLExpr, dsLet, dsLit ) where
8
9 #include "HsVersions.h"
10
11
12 import Match            ( matchWrapper, matchSimply, matchSinglePat )
13 import MatchLit         ( dsLit, dsOverLit )
14 import DsBinds          ( dsHsNestedBinds )
15 import DsGRHSs          ( dsGuarded )
16 import DsListComp       ( dsListComp, dsPArrComp )
17 import DsUtils          ( mkErrorAppDs, mkStringExpr, mkConsExpr, mkNilExpr,
18                           extractMatchResult, cantFailMatchResult, matchCanFail,
19                           mkCoreTupTy, selectSimpleMatchVarL, lookupEvidence )
20 import DsArrows         ( dsProcExpr )
21 import DsMonad
22
23 #ifdef GHCI
24         -- Template Haskell stuff iff bootstrapped
25 import DsMeta           ( dsBracket )
26 #endif
27
28 import HsSyn
29 import TcHsSyn          ( hsPatType )
30
31 -- NB: The desugarer, which straddles the source and Core worlds, sometimes
32 --     needs to see source types (newtypes etc), and sometimes not
33 --     So WATCH OUT; check each use of split*Ty functions.
34 -- Sigh.  This is a pain.
35
36 import TcType           ( tcSplitAppTy, tcSplitFunTys, tcTyConAppTyCon, 
37                           tcTyConAppArgs, isUnLiftedType, Type, mkAppTy )
38 import Type             ( funArgTy, splitFunTys, isUnboxedTupleType, mkFunTy )
39 import CoreSyn
40 import CoreUtils        ( exprType, mkIfThenElse, bindNonRec )
41
42 import CostCentre       ( mkUserCC )
43 import Id               ( Id, idType, idName, idDataCon )
44 import PrelInfo         ( rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID )
45 import DataCon          ( DataCon, dataConWrapId, dataConFieldLabels, dataConInstOrigArgTys )
46 import DataCon          ( isVanillaDataCon )
47 import TyCon            ( FieldLabel, tyConDataCons )
48 import TysWiredIn       ( tupleCon )
49 import BasicTypes       ( RecFlag(..), Boxity(..), ipNameName )
50 import PrelNames        ( toPName,
51                           returnMName, bindMName, thenMName, failMName,
52                           mfixName )
53 import SrcLoc           ( Located(..), unLoc, getLoc, noLoc )
54 import Util             ( zipEqual, zipWithEqual )
55 import Bag              ( bagToList )
56 import Outputable
57 import FastString
58 \end{code}
59
60
61 %************************************************************************
62 %*                                                                      *
63 \subsection{dsLet}
64 %*                                                                      *
65 %************************************************************************
66
67 @dsLet@ is a match-result transformer, taking the @MatchResult@ for the body
68 and transforming it into one for the let-bindings enclosing the body.
69
70 This may seem a bit odd, but (source) let bindings can contain unboxed
71 binds like
72 \begin{verbatim}
73         C x# = e
74 \end{verbatim}
75 This must be transformed to a case expression and, if the type has
76 more than one constructor, may fail.
77
78 \begin{code}
79 dsLet :: [HsBindGroup Id] -> CoreExpr -> DsM CoreExpr
80 dsLet groups body = foldlDs dsBindGroup body (reverse groups)
81
82 dsBindGroup :: CoreExpr -> HsBindGroup Id -> DsM CoreExpr
83 dsBindGroup body (HsIPBinds binds)
84   = foldlDs dsIPBind body binds
85   where
86     dsIPBind body (L _ (IPBind n e))
87         = dsLExpr e     `thenDs` \ e' ->
88           returnDs (Let (NonRec (ipNameName n) e') body)
89
90 -- Special case for bindings which bind unlifted variables
91 -- We need to do a case right away, rather than building
92 -- a tuple and doing selections.
93 -- Silently ignore INLINE pragmas...
94 dsBindGroup body bind@(HsBindGroup hsbinds sigs is_rec)
95   | [L _ (AbsBinds [] [] exports inlines binds)] <- bagToList hsbinds,
96     or [isUnLiftedType (idType g) | (_, g, l) <- exports]
97   = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
98         -- Unlifted bindings are always non-recursive
99         -- and are always a Fun or Pat monobind
100         --
101         -- ToDo: in some bizarre case it's conceivable that there
102         --       could be dict binds in the 'binds'.  (See the notes
103         --       below.  Then pattern-match would fail.  Urk.)
104     let
105       body_w_exports               = foldr bind_export body exports
106       bind_export (tvs, g, l) body = ASSERT( null tvs )
107                                      bindNonRec g (Var l) body
108
109       mk_error_app pat = mkErrorAppDs iRREFUT_PAT_ERROR_ID
110                                     (exprType body)
111                                     (showSDoc (ppr pat))
112     in
113     case bagToList binds of
114       [L loc (FunBind (L _ fun) _ matches)]
115         -> putSrcSpanDs loc                                     $
116            matchWrapper (FunRhs (idName fun)) matches           `thenDs` \ (args, rhs) ->
117            ASSERT( null args )  -- Functions aren't lifted
118            returnDs (bindNonRec fun rhs body_w_exports)
119
120       [L loc (PatBind pat grhss ty)]
121         -> putSrcSpanDs loc                     $
122            dsGuarded grhss ty                   `thenDs` \ rhs ->
123            mk_error_app pat                     `thenDs` \ error_expr ->
124            matchSimply rhs PatBindRhs pat body_w_exports error_expr
125
126       other -> pprPanic "dsLet: unlifted" (ppr bind $$ ppr body)
127
128 -- Ordinary case for bindings
129 dsBindGroup body (HsBindGroup binds sigs is_rec)
130   = dsHsNestedBinds binds       `thenDs` \ prs ->
131     returnDs (Let (Rec prs) body)
132         -- Use a Rec regardless of is_rec. 
133         -- Why? Because it allows the binds to be all
134         -- mixed up, which is what happens in one rare case
135         -- Namely, for an AbsBind with no tyvars and no dicts,
136         --         but which does have dictionary bindings.
137         -- See notes with TcSimplify.inferLoop [NO TYVARS]
138         -- It turned out that wrapping a Rec here was the easiest solution
139         --
140         -- NB The previous case dealt with unlifted bindings, so we
141         --    only have to deal with lifted ones now; so Rec is ok
142 \end{code}      
143
144 %************************************************************************
145 %*                                                                      *
146 \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
147 %*                                                                      *
148 %************************************************************************
149
150 \begin{code}
151 dsLExpr :: LHsExpr Id -> DsM CoreExpr
152 dsLExpr (L loc e) = putSrcSpanDs loc $ dsExpr e
153
154 dsExpr :: HsExpr Id -> DsM CoreExpr
155
156 dsExpr (HsPar e)              = dsLExpr e
157 dsExpr (ExprWithTySigOut e _) = dsLExpr e
158 dsExpr (HsVar var)            = returnDs (Var var)
159 dsExpr (HsIPVar ip)           = returnDs (Var (ipNameName ip))
160 dsExpr (HsLit lit)            = dsLit lit
161 dsExpr (HsOverLit lit)        = dsOverLit lit
162
163 dsExpr (NegApp expr neg_expr) 
164   = do  { core_expr <- dsLExpr expr
165         ; core_neg  <- dsExpr neg_expr
166         ; return (core_neg `App` core_expr) }
167
168 dsExpr expr@(HsLam a_Match)
169   = matchWrapper LambdaExpr a_Match     `thenDs` \ (binders, matching_code) ->
170     returnDs (mkLams binders matching_code)
171
172 dsExpr expr@(HsApp fun arg)      
173   = dsLExpr fun         `thenDs` \ core_fun ->
174     dsLExpr arg         `thenDs` \ core_arg ->
175     returnDs (core_fun `App` core_arg)
176 \end{code}
177
178 Operator sections.  At first it looks as if we can convert
179 \begin{verbatim}
180         (expr op)
181 \end{verbatim}
182 to
183 \begin{verbatim}
184         \x -> op expr x
185 \end{verbatim}
186
187 But no!  expr might be a redex, and we can lose laziness badly this
188 way.  Consider
189 \begin{verbatim}
190         map (expr op) xs
191 \end{verbatim}
192 for example.  So we convert instead to
193 \begin{verbatim}
194         let y = expr in \x -> op y x
195 \end{verbatim}
196 If \tr{expr} is actually just a variable, say, then the simplifier
197 will sort it out.
198
199 \begin{code}
200 dsExpr (OpApp e1 op _ e2)
201   = dsLExpr op                                          `thenDs` \ core_op ->
202     -- for the type of y, we need the type of op's 2nd argument
203     dsLExpr e1                          `thenDs` \ x_core ->
204     dsLExpr e2                          `thenDs` \ y_core ->
205     returnDs (mkApps core_op [x_core, y_core])
206     
207 dsExpr (SectionL expr op)
208   = dsLExpr op                                          `thenDs` \ core_op ->
209     -- for the type of y, we need the type of op's 2nd argument
210     let
211         (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
212         -- Must look through an implicit-parameter type; 
213         -- newtype impossible; hence Type.splitFunTys
214     in
215     dsLExpr expr                                `thenDs` \ x_core ->
216     newSysLocalDs x_ty                  `thenDs` \ x_id ->
217     newSysLocalDs y_ty                  `thenDs` \ y_id ->
218
219     returnDs (bindNonRec x_id x_core $
220               Lam y_id (mkApps core_op [Var x_id, Var y_id]))
221
222 -- dsLExpr (SectionR op expr)   -- \ x -> op x expr
223 dsExpr (SectionR op expr)
224   = dsLExpr op                  `thenDs` \ core_op ->
225     -- for the type of x, we need the type of op's 2nd argument
226     let
227         (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
228         -- See comment with SectionL
229     in
230     dsLExpr expr                                `thenDs` \ y_core ->
231     newSysLocalDs x_ty                  `thenDs` \ x_id ->
232     newSysLocalDs y_ty                  `thenDs` \ y_id ->
233
234     returnDs (bindNonRec y_id y_core $
235               Lam x_id (mkApps core_op [Var x_id, Var y_id]))
236
237 dsExpr (HsSCC cc expr)
238   = dsLExpr expr                        `thenDs` \ core_expr ->
239     getModuleDs                 `thenDs` \ mod_name ->
240     returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
241
242
243 -- hdaume: core annotation
244
245 dsExpr (HsCoreAnn fs expr)
246   = dsLExpr expr        `thenDs` \ core_expr ->
247     returnDs (Note (CoreNote $ unpackFS fs) core_expr)
248
249 -- Special case to handle unboxed tuple patterns; they can't appear nested
250 dsExpr (HsCase discrim matches@(MatchGroup _ ty))
251  | isUnboxedTupleType (funArgTy ty)
252  =  dsLExpr discrim                     `thenDs` \ core_discrim ->
253     matchWrapper CaseAlt matches        `thenDs` \ ([discrim_var], matching_code) ->
254     case matching_code of
255         Case (Var x) bndr ty alts | x == discrim_var -> 
256                 returnDs (Case core_discrim bndr ty alts)
257         _ -> panic ("dsLExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
258
259 dsExpr (HsCase discrim matches)
260   = dsLExpr discrim                     `thenDs` \ core_discrim ->
261     matchWrapper CaseAlt matches        `thenDs` \ ([discrim_var], matching_code) ->
262     returnDs (bindNonRec discrim_var core_discrim matching_code)
263
264 dsExpr (HsLet binds body)
265   = dsLExpr body                `thenDs` \ body' ->
266     dsLet binds body'
267
268 -- We need the `ListComp' form to use `deListComp' (rather than the "do" form)
269 -- because the interpretation of `stmts' depends on what sort of thing it is.
270 --
271 dsExpr (HsDo ListComp stmts body result_ty)
272   =     -- Special case for list comprehensions
273     dsListComp stmts body elt_ty
274   where
275     [elt_ty] = tcTyConAppArgs result_ty
276
277 dsExpr (HsDo DoExpr stmts body result_ty)
278   = dsDo stmts body result_ty
279
280 dsExpr (HsDo (MDoExpr tbl) stmts body result_ty)
281   = dsMDo tbl stmts body result_ty
282
283 dsExpr (HsDo PArrComp stmts body result_ty)
284   =     -- Special case for array comprehensions
285     dsPArrComp (map unLoc stmts) body elt_ty
286   where
287     [elt_ty] = tcTyConAppArgs result_ty
288
289 dsExpr (HsIf guard_expr then_expr else_expr)
290   = dsLExpr guard_expr  `thenDs` \ core_guard ->
291     dsLExpr then_expr   `thenDs` \ core_then ->
292     dsLExpr else_expr   `thenDs` \ core_else ->
293     returnDs (mkIfThenElse core_guard core_then core_else)
294 \end{code}
295
296
297 \noindent
298 \underline{\bf Type lambda and application}
299 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~
300 \begin{code}
301 dsExpr (TyLam tyvars expr)
302   = dsLExpr expr `thenDs` \ core_expr ->
303     returnDs (mkLams tyvars core_expr)
304
305 dsExpr (TyApp expr tys)
306   = dsLExpr expr                `thenDs` \ core_expr ->
307     returnDs (mkTyApps core_expr tys)
308 \end{code}
309
310
311 \noindent
312 \underline{\bf Various data construction things}
313 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
314 \begin{code}
315 dsExpr (ExplicitList ty xs)
316   = go xs
317   where
318     go []     = returnDs (mkNilExpr ty)
319     go (x:xs) = dsLExpr x                               `thenDs` \ core_x ->
320                 go xs                                   `thenDs` \ core_xs ->
321                 returnDs (mkConsExpr ty core_x core_xs)
322
323 -- we create a list from the array elements and convert them into a list using
324 -- `PrelPArr.toP'
325 --
326 --  * the main disadvantage to this scheme is that `toP' traverses the list
327 --   twice: once to determine the length and a second time to put to elements
328 --   into the array; this inefficiency could be avoided by exposing some of
329 --   the innards of `PrelPArr' to the compiler (ie, have a `PrelPArrBase') so
330 --   that we can exploit the fact that we already know the length of the array
331 --   here at compile time
332 --
333 dsExpr (ExplicitPArr ty xs)
334   = dsLookupGlobalId toPName                            `thenDs` \toP      ->
335     dsExpr (ExplicitList ty xs)                         `thenDs` \coreList ->
336     returnDs (mkApps (Var toP) [Type ty, coreList])
337
338 dsExpr (ExplicitTuple expr_list boxity)
339   = mappM dsLExpr expr_list       `thenDs` \ core_exprs  ->
340     returnDs (mkConApp (tupleCon boxity (length expr_list))
341                        (map (Type .  exprType) core_exprs ++ core_exprs))
342
343 dsExpr (ArithSeq expr (From from))
344   = dsExpr expr           `thenDs` \ expr2 ->
345     dsLExpr from          `thenDs` \ from2 ->
346     returnDs (App expr2 from2)
347
348 dsExpr (ArithSeq expr (FromTo from two))
349   = dsExpr expr           `thenDs` \ expr2 ->
350     dsLExpr from          `thenDs` \ from2 ->
351     dsLExpr two           `thenDs` \ two2 ->
352     returnDs (mkApps expr2 [from2, two2])
353
354 dsExpr (ArithSeq expr (FromThen from thn))
355   = dsExpr expr           `thenDs` \ expr2 ->
356     dsLExpr from          `thenDs` \ from2 ->
357     dsLExpr thn           `thenDs` \ thn2 ->
358     returnDs (mkApps expr2 [from2, thn2])
359
360 dsExpr (ArithSeq expr (FromThenTo from thn two))
361   = dsExpr expr           `thenDs` \ expr2 ->
362     dsLExpr from          `thenDs` \ from2 ->
363     dsLExpr thn           `thenDs` \ thn2 ->
364     dsLExpr two           `thenDs` \ two2 ->
365     returnDs (mkApps expr2 [from2, thn2, two2])
366
367 dsExpr (PArrSeq expr (FromTo from two))
368   = dsExpr expr           `thenDs` \ expr2 ->
369     dsLExpr from          `thenDs` \ from2 ->
370     dsLExpr two           `thenDs` \ two2 ->
371     returnDs (mkApps expr2 [from2, two2])
372
373 dsExpr (PArrSeq expr (FromThenTo from thn two))
374   = dsExpr expr           `thenDs` \ expr2 ->
375     dsLExpr from          `thenDs` \ from2 ->
376     dsLExpr thn           `thenDs` \ thn2 ->
377     dsLExpr two           `thenDs` \ two2 ->
378     returnDs (mkApps expr2 [from2, thn2, two2])
379
380 dsExpr (PArrSeq expr _)
381   = panic "DsExpr.dsExpr: Infinite parallel array!"
382     -- the parser shouldn't have generated it and the renamer and typechecker
383     -- shouldn't have let it through
384 \end{code}
385
386 \noindent
387 \underline{\bf Record construction and update}
388 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
389 For record construction we do this (assuming T has three arguments)
390 \begin{verbatim}
391         T { op2 = e }
392 ==>
393         let err = /\a -> recConErr a 
394         T (recConErr t1 "M.lhs/230/op1") 
395           e 
396           (recConErr t1 "M.lhs/230/op3")
397 \end{verbatim}
398 @recConErr@ then converts its arugment string into a proper message
399 before printing it as
400 \begin{verbatim}
401         M.lhs, line 230: missing field op1 was evaluated
402 \end{verbatim}
403
404 We also handle @C{}@ as valid construction syntax for an unlabelled
405 constructor @C@, setting all of @C@'s fields to bottom.
406
407 \begin{code}
408 dsExpr (RecordCon (L _ data_con_id) con_expr rbinds)
409   = dsExpr con_expr     `thenDs` \ con_expr' ->
410     let
411         (arg_tys, _) = tcSplitFunTys (exprType con_expr')
412         -- A newtype in the corner should be opaque; 
413         -- hence TcType.tcSplitFunTys
414
415         mk_arg (arg_ty, lbl)    -- Selector id has the field label as its name
416           = case [rhs | (L _ sel_id, rhs) <- rbinds, lbl == idName sel_id] of
417               (rhs:rhss) -> ASSERT( null rhss )
418                             dsLExpr rhs
419               []         -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
420         unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
421
422         labels = dataConFieldLabels (idDataCon data_con_id)
423         -- The data_con_id is guaranteed to be the wrapper id of the constructor
424     in
425
426     (if null labels
427         then mappM unlabelled_bottom arg_tys
428         else mappM mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
429         `thenDs` \ con_args ->
430
431     returnDs (mkApps con_expr' con_args)
432 \end{code}
433
434 Record update is a little harder. Suppose we have the decl:
435 \begin{verbatim}
436         data T = T1 {op1, op2, op3 :: Int}
437                | T2 {op4, op2 :: Int}
438                | T3
439 \end{verbatim}
440 Then we translate as follows:
441 \begin{verbatim}
442         r { op2 = e }
443 ===>
444         let op2 = e in
445         case r of
446           T1 op1 _ op3 -> T1 op1 op2 op3
447           T2 op4 _     -> T2 op4 op2
448           other        -> recUpdError "M.lhs/230"
449 \end{verbatim}
450 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
451 RHSs, and do not generate a Core constructor application directly, because the constructor
452 might do some argument-evaluation first; and may have to throw away some
453 dictionaries.
454
455 \begin{code}
456 dsExpr (RecordUpd record_expr [] record_in_ty record_out_ty)
457   = dsLExpr record_expr
458
459 dsExpr expr@(RecordUpd record_expr rbinds record_in_ty record_out_ty)
460   = dsLExpr record_expr         `thenDs` \ record_expr' ->
461
462         -- Desugar the rbinds, and generate let-bindings if
463         -- necessary so that we don't lose sharing
464
465     let
466         in_inst_tys  = tcTyConAppArgs record_in_ty      -- Newtype opaque
467         out_inst_tys = tcTyConAppArgs record_out_ty     -- Newtype opaque
468         in_out_ty    = mkFunTy record_in_ty record_out_ty
469
470         mk_val_arg field old_arg_id 
471           = case [rhs | (L _ sel_id, rhs) <- rbinds, field == idName sel_id] of
472               (rhs:rest) -> ASSERT(null rest) rhs
473               []         -> nlHsVar old_arg_id
474
475         mk_alt con
476           = newSysLocalsDs (dataConInstOrigArgTys con in_inst_tys) `thenDs` \ arg_ids ->
477                 -- This call to dataConArgTys won't work for existentials
478                 -- but existentials don't have record types anyway
479             let 
480                 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
481                                         (dataConFieldLabels con) arg_ids
482                 rhs = foldl (\a b -> nlHsApp a b)
483                         (noLoc $ TyApp (nlHsVar (dataConWrapId con)) 
484                                 out_inst_tys)
485                           val_args
486             in
487             returnDs (mkSimpleMatch [noLoc $ ConPatOut (noLoc con) [] [] emptyLHsBinds 
488                                                        (PrefixCon (map nlVarPat arg_ids)) record_in_ty]
489                                     rhs)
490     in
491         -- Record stuff doesn't work for existentials
492         -- The type checker checks for this, but we need 
493         -- worry only about the constructors that are to be updated
494     ASSERT2( all isVanillaDataCon cons_to_upd, ppr expr )
495
496         -- It's important to generate the match with matchWrapper,
497         -- and the right hand sides with applications of the wrapper Id
498         -- so that everything works when we are doing fancy unboxing on the
499         -- constructor aguments.
500     mappM mk_alt cons_to_upd                            `thenDs` \ alts ->
501     matchWrapper RecUpd (MatchGroup alts in_out_ty)     `thenDs` \ ([discrim_var], matching_code) ->
502
503     returnDs (bindNonRec discrim_var record_expr' matching_code)
504
505   where
506     updated_fields :: [FieldLabel]
507     updated_fields = [ idName sel_id | (L _ sel_id,_) <- rbinds]
508
509         -- Get the type constructor from the record_in_ty
510         -- so that we are sure it'll have all its DataCons
511         -- (In GHCI, it's possible that some TyCons may not have all
512         --  their constructors, in a module-loop situation.)
513     tycon       = tcTyConAppTyCon record_in_ty
514     data_cons   = tyConDataCons tycon
515     cons_to_upd = filter has_all_fields data_cons
516
517     has_all_fields :: DataCon -> Bool
518     has_all_fields con_id 
519       = all (`elem` con_fields) updated_fields
520       where
521         con_fields = dataConFieldLabels con_id
522 \end{code}
523
524
525 \noindent
526 \underline{\bf Dictionary lambda and application}
527 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
528 @DictLam@ and @DictApp@ turn into the regular old things.
529 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
530 complicated; reminiscent of fully-applied constructors.
531 \begin{code}
532 dsExpr (DictLam dictvars expr)
533   = dsLExpr expr `thenDs` \ core_expr ->
534     returnDs (mkLams dictvars core_expr)
535
536 ------------------
537
538 dsExpr (DictApp expr dicts)     -- becomes a curried application
539   = dsLExpr expr                        `thenDs` \ core_expr ->
540     returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
541 \end{code}
542
543 Here is where we desugar the Template Haskell brackets and escapes
544
545 \begin{code}
546 -- Template Haskell stuff
547
548 #ifdef GHCI     /* Only if bootstrapping */
549 dsExpr (HsBracketOut x ps) = dsBracket x ps
550 dsExpr (HsSpliceE s)       = pprPanic "dsExpr:splice" (ppr s)
551 #endif
552
553 -- Arrow notation extension
554 dsExpr (HsProc pat cmd) = dsProcExpr pat cmd
555 \end{code}
556
557
558 \begin{code}
559
560 #ifdef DEBUG
561 -- HsSyn constructs that just shouldn't be here:
562 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
563 #endif
564
565 \end{code}
566
567 %--------------------------------------------------------------------
568
569 Desugar 'do' and 'mdo' expressions (NOT list comprehensions, they're
570 handled in DsListComp).  Basically does the translation given in the
571 Haskell 98 report:
572
573 \begin{code}
574 dsDo    :: [LStmt Id]
575         -> LHsExpr Id
576         -> Type                 -- Type of the whole expression
577         -> DsM CoreExpr
578
579 dsDo stmts body result_ty
580   = go (map unLoc stmts)
581   where
582     go [] = dsLExpr body
583     
584     go (ExprStmt rhs then_expr _ : stmts)
585       = do { rhs2 <- dsLExpr rhs
586            ; then_expr2 <- dsExpr then_expr
587            ; rest <- go stmts
588            ; returnDs (mkApps then_expr2 [rhs2, rest]) }
589     
590     go (LetStmt binds : stmts)
591       = do { rest <- go stmts
592            ; dsLet binds rest }
593         
594     go (BindStmt pat rhs bind_op fail_op : stmts)
595       = do { body  <- go stmts
596            ; var   <- selectSimpleMatchVarL pat
597            ; match <- matchSinglePat (Var var) (StmtCtxt DoExpr) pat
598                                   result_ty (cantFailMatchResult body)
599            ; match_code <- handle_failure pat match fail_op
600            ; rhs'       <- dsLExpr rhs
601            ; bind_op'   <- dsExpr bind_op
602            ; returnDs (mkApps bind_op' [rhs', Lam var match_code]) }
603     
604     -- In a do expression, pattern-match failure just calls
605     -- the monadic 'fail' rather than throwing an exception
606     handle_failure pat match fail_op
607       | matchCanFail match
608       = do { fail_op' <- dsExpr fail_op
609            ; fail_msg <- mkStringExpr (mk_fail_msg pat)
610            ; extractMatchResult match (App fail_op' fail_msg) }
611       | otherwise
612       = extractMatchResult match (error "It can't fail") 
613
614 mk_fail_msg pat = "Pattern match failure in do expression at " ++ 
615                   showSDoc (ppr (getLoc pat))
616 \end{code}
617
618 Translation for RecStmt's: 
619 -----------------------------
620 We turn (RecStmt [v1,..vn] stmts) into:
621   
622   (v1,..,vn) <- mfix (\~(v1,..vn). do stmts
623                                       return (v1,..vn))
624
625 \begin{code}
626 dsMDo   :: PostTcTable
627         -> [LStmt Id]
628         -> LHsExpr Id
629         -> Type                 -- Type of the whole expression
630         -> DsM CoreExpr
631
632 dsMDo tbl stmts body result_ty
633   = go (map unLoc stmts)
634   where
635     (m_ty, b_ty) = tcSplitAppTy result_ty       -- result_ty must be of the form (m b)
636     mfix_id   = lookupEvidence tbl mfixName
637     return_id = lookupEvidence tbl returnMName
638     bind_id   = lookupEvidence tbl bindMName
639     then_id   = lookupEvidence tbl thenMName
640     fail_id   = lookupEvidence tbl failMName
641     ctxt      = MDoExpr tbl
642
643     go [] = dsLExpr body
644     
645     go (LetStmt binds : stmts)
646       = do { rest <- go stmts
647            ; dsLet binds rest }
648
649     go (ExprStmt rhs _ rhs_ty : stmts)
650       = do { rhs2 <- dsLExpr rhs
651            ; rest <- go stmts
652            ; returnDs (mkApps (Var then_id) [Type rhs_ty, Type b_ty, rhs2, rest]) }
653     
654     go (BindStmt pat rhs _ _ : stmts)
655       = do { body  <- go stmts
656            ; var   <- selectSimpleMatchVarL pat
657            ; match <- matchSinglePat (Var var) (StmtCtxt ctxt) pat
658                                   result_ty (cantFailMatchResult body)
659            ; fail_msg   <- mkStringExpr (mk_fail_msg pat)
660            ; let fail_expr = mkApps (Var fail_id) [Type b_ty, fail_msg]
661            ; match_code <- extractMatchResult match fail_expr
662
663            ; rhs'       <- dsLExpr rhs
664            ; returnDs (mkApps (Var bind_id) [Type (hsPatType pat), Type b_ty, 
665                                              rhs', Lam var match_code]) }
666     
667     go (RecStmt rec_stmts later_ids rec_ids rec_rets binds : stmts)
668       = ASSERT( length rec_ids > 0 )
669         ASSERT( length rec_ids == length rec_rets )
670         go (new_bind_stmt : let_stmt : stmts)
671       where
672         new_bind_stmt = mkBindStmt (mk_tup_pat later_pats) mfix_app
673         let_stmt = LetStmt [HsBindGroup binds [] Recursive]
674
675         
676                 -- Remove the later_ids that appear (without fancy coercions) 
677                 -- in rec_rets, because there's no need to knot-tie them separately
678                 -- See Note [RecStmt] in HsExpr
679         later_ids'   = filter (`notElem` mono_rec_ids) later_ids
680         mono_rec_ids = [ id | HsVar id <- rec_rets ]
681     
682         mfix_app = nlHsApp (noLoc $ TyApp (nlHsVar mfix_id) [tup_ty]) mfix_arg
683         mfix_arg = noLoc $ HsLam (MatchGroup [mkSimpleMatch [mfix_pat] body]
684                                              (mkFunTy tup_ty body_ty))
685
686         -- The rec_tup_pat must bind the rec_ids only; remember that the 
687         --      trimmed_laters may share the same Names
688         -- Meanwhile, the later_pats must bind the later_vars
689         rec_tup_pats = map mk_wild_pat later_ids' ++ map nlVarPat rec_ids
690         later_pats   = map nlVarPat    later_ids' ++ map mk_later_pat rec_ids
691         rets         = map nlHsVar     later_ids' ++ map noLoc rec_rets
692
693         mfix_pat = noLoc $ LazyPat $ mk_tup_pat rec_tup_pats
694         body     = noLoc $ HsDo ctxt rec_stmts return_app body_ty
695         body_ty = mkAppTy m_ty tup_ty
696         tup_ty  = mkCoreTupTy (map idType (later_ids' ++ rec_ids))
697                   -- mkCoreTupTy deals with singleton case
698
699         return_app  = nlHsApp (noLoc $ TyApp (nlHsVar return_id) [tup_ty]) 
700                               (mk_ret_tup rets)
701
702         mk_wild_pat :: Id -> LPat Id 
703         mk_wild_pat v = noLoc $ WildPat $ idType v
704
705         mk_later_pat :: Id -> LPat Id
706         mk_later_pat v | v `elem` later_ids' = mk_wild_pat v
707                        | otherwise           = nlVarPat v
708
709         mk_tup_pat :: [LPat Id] -> LPat Id
710         mk_tup_pat [p] = p
711         mk_tup_pat ps  = noLoc $ TuplePat ps Boxed
712
713         mk_ret_tup :: [LHsExpr Id] -> LHsExpr Id
714         mk_ret_tup [r] = r
715         mk_ret_tup rs  = noLoc $ ExplicitTuple rs Boxed
716 \end{code}