2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[DsExpr]{Matching expressions (Exprs)}
7 module DsExpr ( dsExpr, dsLExpr, dsLocalBinds, dsValBinds, dsLit ) where
9 #include "HsVersions.h"
10 #if defined(GHCI) && defined(BREAKPOINT)
11 import Foreign.StablePtr ( newStablePtr, castStablePtrToPtr )
12 import GHC.Exts ( Ptr(..), Int(..), addr2Int# )
13 import IOEnv ( ioToIOEnv )
14 import PrelNames ( breakpointJumpName )
15 import TysWiredIn ( unitTy )
16 import TypeRep ( Type(..) )
19 import Match ( matchWrapper, matchSinglePat, matchEquations )
20 import MatchLit ( dsLit, dsOverLit )
21 import DsBinds ( dsLHsBinds, dsCoercion )
22 import DsGRHSs ( dsGuarded )
23 import DsListComp ( dsListComp, dsPArrComp )
24 import DsUtils ( mkErrorAppDs, mkStringExpr, mkConsExpr, mkNilExpr,
25 extractMatchResult, cantFailMatchResult, matchCanFail,
26 mkCoreTupTy, selectSimpleMatchVarL, lookupEvidence, selectMatchVar )
27 import DsArrows ( dsProcExpr )
31 -- Template Haskell stuff iff bootstrapped
32 import DsMeta ( dsBracket )
36 import TcHsSyn ( hsPatType, mkVanillaTuplePat )
38 -- NB: The desugarer, which straddles the source and Core worlds, sometimes
39 -- needs to see source types (newtypes etc), and sometimes not
40 -- So WATCH OUT; check each use of split*Ty functions.
41 -- Sigh. This is a pain.
43 import TcType ( tcSplitAppTy, tcSplitFunTys, tcTyConAppTyCon,
44 tcTyConAppArgs, isUnLiftedType, Type, mkAppTy )
45 import Type ( funArgTy, splitFunTys, isUnboxedTupleType, mkFunTy )
47 import CoreUtils ( exprType, mkIfThenElse, bindNonRec )
49 import CostCentre ( mkUserCC )
50 import Id ( Id, idType, idName, idDataCon )
51 import PrelInfo ( rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID )
52 import DataCon ( DataCon, dataConWrapId, dataConFieldLabels, dataConInstOrigArgTys )
53 import DataCon ( isVanillaDataCon )
54 import TyCon ( FieldLabel, tyConDataCons )
55 import TysWiredIn ( tupleCon )
56 import BasicTypes ( RecFlag(..), Boxity(..), ipNameName )
57 import PrelNames ( toPName,
58 returnMName, bindMName, thenMName, failMName,
60 import SrcLoc ( Located(..), unLoc, getLoc, noLoc )
61 import Util ( zipEqual, zipWithEqual )
62 import Bag ( bagToList )
68 %************************************************************************
70 dsLocalBinds, dsValBinds
72 %************************************************************************
75 dsLocalBinds :: HsLocalBinds Id -> CoreExpr -> DsM CoreExpr
76 dsLocalBinds EmptyLocalBinds body = return body
77 dsLocalBinds (HsValBinds binds) body = dsValBinds binds body
78 dsLocalBinds (HsIPBinds binds) body = dsIPBinds binds body
80 -------------------------
81 dsValBinds :: HsValBinds Id -> CoreExpr -> DsM CoreExpr
82 dsValBinds (ValBindsOut binds _) body = foldrDs ds_val_bind body binds
84 -------------------------
85 dsIPBinds (IPBinds ip_binds dict_binds) body
86 = do { prs <- dsLHsBinds dict_binds
87 ; let inner = foldr (\(x,r) e -> Let (NonRec x r) e) body prs
88 ; foldrDs ds_ip_bind inner ip_binds }
90 ds_ip_bind (L _ (IPBind n e)) body
91 = dsLExpr e `thenDs` \ e' ->
92 returnDs (Let (NonRec (ipNameName n) e') body)
94 -------------------------
95 ds_val_bind :: (RecFlag, LHsBinds Id) -> CoreExpr -> DsM CoreExpr
96 -- Special case for bindings which bind unlifted variables
97 -- We need to do a case right away, rather than building
98 -- a tuple and doing selections.
99 -- Silently ignore INLINE and SPECIALISE pragmas...
100 ds_val_bind (NonRecursive, hsbinds) body
101 | [L _ (AbsBinds [] [] exports binds)] <- bagToList hsbinds,
102 (L loc bind : null_binds) <- bagToList binds,
104 || isUnboxedTupleBind bind
105 || or [isUnLiftedType (idType g) | (_, g, _, _) <- exports]
107 body_w_exports = foldr bind_export body exports
108 bind_export (tvs, g, l, _) body = ASSERT( null tvs )
109 bindNonRec g (Var l) body
111 ASSERT (null null_binds)
112 -- Non-recursive, non-overloaded bindings only come in ones
113 -- ToDo: in some bizarre case it's conceivable that there
114 -- could be dict binds in the 'binds'. (See the notes
115 -- below. Then pattern-match would fail. Urk.)
118 FunBind { fun_id = L _ fun, fun_matches = matches, fun_co_fn = co_fn }
119 -> matchWrapper (FunRhs (idName fun)) matches `thenDs` \ (args, rhs) ->
120 ASSERT( null args ) -- Functions aren't lifted
121 ASSERT( isIdCoercion co_fn )
122 returnDs (bindNonRec fun rhs body_w_exports)
124 PatBind {pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty }
125 -> -- let C x# y# = rhs in body
126 -- ==> case rhs of C x# y# -> body
128 do { rhs <- dsGuarded grhss ty
129 ; let upat = unLoc pat
130 eqn = EqnInfo { eqn_wrap = idWrapper, eqn_pats = [upat],
131 eqn_rhs = cantFailMatchResult body_w_exports }
132 ; var <- selectMatchVar upat ty
133 ; result <- matchEquations PatBindRhs [var] [eqn] (exprType body)
134 ; return (scrungleMatch var rhs result) }
136 other -> pprPanic "dsLet: unlifted" (pprLHsBinds hsbinds $$ ppr body)
139 -- Ordinary case for bindings; none should be unlifted
140 ds_val_bind (is_rec, binds) body
141 = do { prs <- dsLHsBinds binds
142 ; ASSERT( not (any (isUnLiftedType . idType . fst) prs) )
145 other -> return (Let (Rec prs) body) }
146 -- Use a Rec regardless of is_rec.
147 -- Why? Because it allows the binds to be all
148 -- mixed up, which is what happens in one rare case
149 -- Namely, for an AbsBind with no tyvars and no dicts,
150 -- but which does have dictionary bindings.
151 -- See notes with TcSimplify.inferLoop [NO TYVARS]
152 -- It turned out that wrapping a Rec here was the easiest solution
154 -- NB The previous case dealt with unlifted bindings, so we
155 -- only have to deal with lifted ones now; so Rec is ok
157 isUnboxedTupleBind :: HsBind Id -> Bool
158 isUnboxedTupleBind (PatBind { pat_rhs_ty = ty }) = isUnboxedTupleType ty
159 isUnboxedTupleBind other = False
161 scrungleMatch :: Id -> CoreExpr -> CoreExpr -> CoreExpr
162 -- Returns something like (let var = scrut in body)
163 -- but if var is an unboxed-tuple type, it inlines it in a fragile way
164 -- Special case to handle unboxed tuple patterns; they can't appear nested
166 -- case e of (# p1, p2 #) -> rhs
168 -- case e of (# x1, x2 #) -> ... match p1, p2 ...
170 -- let x = e in case x of ....
172 -- But there may be a big
173 -- let fail = ... in case e of ...
174 -- wrapping the whole case, which complicates matters slightly
175 -- It all seems a bit fragile. Test is dsrun013.
177 scrungleMatch var scrut body
178 | isUnboxedTupleType (idType var) = scrungle body
179 | otherwise = bindNonRec var scrut body
181 scrungle (Case (Var x) bndr ty alts)
182 | x == var = Case scrut bndr ty alts
183 scrungle (Let binds body) = Let binds (scrungle body)
184 scrungle other = panic ("scrungleMatch: tuple pattern:\n" ++ showSDoc (ppr other))
187 %************************************************************************
189 \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
191 %************************************************************************
194 dsLExpr :: LHsExpr Id -> DsM CoreExpr
195 dsLExpr (L loc e) = putSrcSpanDs loc $ dsExpr e
197 dsExpr :: HsExpr Id -> DsM CoreExpr
199 dsExpr (HsPar e) = dsLExpr e
200 dsExpr (ExprWithTySigOut e _) = dsLExpr e
201 dsExpr (HsVar var) = returnDs (Var var)
202 dsExpr (HsIPVar ip) = returnDs (Var (ipNameName ip))
203 dsExpr (HsLit lit) = dsLit lit
204 dsExpr (HsOverLit lit) = dsOverLit lit
206 dsExpr (NegApp expr neg_expr)
207 = do { core_expr <- dsLExpr expr
208 ; core_neg <- dsExpr neg_expr
209 ; return (core_neg `App` core_expr) }
211 dsExpr expr@(HsLam a_Match)
212 = matchWrapper LambdaExpr a_Match `thenDs` \ (binders, matching_code) ->
213 returnDs (mkLams binders matching_code)
215 #if defined(GHCI) && defined(BREAKPOINT)
216 dsExpr (HsApp (L _ (HsApp realFun@(L _ (HsCoerce _ fun)) (L loc arg))) _)
218 , idName funId == breakpointJumpName
219 , ids <- filter (not.hasTyVar.idType) (extractIds arg)
220 = do dsWarn (text "Extracted ids:" <+> ppr ids <+> ppr (map idType ids))
221 stablePtr <- ioToIOEnv $ newStablePtr ids
222 -- Yes, I know... I'm gonna burn in hell.
223 let Ptr addr# = castStablePtrToPtr stablePtr
224 funCore <- dsLExpr realFun
225 argCore <- dsLExpr (L loc (HsLit (HsInt (fromIntegral (I# (addr2Int# addr#))))))
226 hvalCore <- dsLExpr (L loc (extractHVals ids))
227 return ((funCore `App` argCore) `App` hvalCore)
228 where extractIds :: HsExpr Id -> [Id]
229 extractIds (HsApp fn arg)
230 | HsVar argId <- unLoc arg
231 = argId:extractIds (unLoc fn)
232 | TyApp arg' ts <- unLoc arg
233 , HsVar argId <- unLoc arg'
234 = error (showSDoc (ppr ts)) -- argId:extractIds (unLoc fn)
236 extractHVals ids = ExplicitList unitTy (map (L loc . HsVar) ids)
237 hasTyVar (TyVarTy _) = True
238 hasTyVar (FunTy a b) = hasTyVar a || hasTyVar b
239 hasTyVar (NoteTy _ t) = hasTyVar t
240 hasTyVar (AppTy a b) = hasTyVar a || hasTyVar b
241 hasTyVar (TyConApp _ ts) = any hasTyVar ts
245 dsExpr expr@(HsApp fun arg)
246 = dsLExpr fun `thenDs` \ core_fun ->
247 dsLExpr arg `thenDs` \ core_arg ->
248 returnDs (core_fun `App` core_arg)
251 Operator sections. At first it looks as if we can convert
260 But no! expr might be a redex, and we can lose laziness badly this
265 for example. So we convert instead to
267 let y = expr in \x -> op y x
269 If \tr{expr} is actually just a variable, say, then the simplifier
273 dsExpr (OpApp e1 op _ e2)
274 = dsLExpr op `thenDs` \ core_op ->
275 -- for the type of y, we need the type of op's 2nd argument
276 dsLExpr e1 `thenDs` \ x_core ->
277 dsLExpr e2 `thenDs` \ y_core ->
278 returnDs (mkApps core_op [x_core, y_core])
280 dsExpr (SectionL expr op)
281 = dsLExpr op `thenDs` \ core_op ->
282 -- for the type of y, we need the type of op's 2nd argument
284 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
285 -- Must look through an implicit-parameter type;
286 -- newtype impossible; hence Type.splitFunTys
288 dsLExpr expr `thenDs` \ x_core ->
289 newSysLocalDs x_ty `thenDs` \ x_id ->
290 newSysLocalDs y_ty `thenDs` \ y_id ->
292 returnDs (bindNonRec x_id x_core $
293 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
295 -- dsLExpr (SectionR op expr) -- \ x -> op x expr
296 dsExpr (SectionR op expr)
297 = dsLExpr op `thenDs` \ core_op ->
298 -- for the type of x, we need the type of op's 2nd argument
300 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
301 -- See comment with SectionL
303 dsLExpr expr `thenDs` \ y_core ->
304 newSysLocalDs x_ty `thenDs` \ x_id ->
305 newSysLocalDs y_ty `thenDs` \ y_id ->
307 returnDs (bindNonRec y_id y_core $
308 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
310 dsExpr (HsSCC cc expr)
311 = dsLExpr expr `thenDs` \ core_expr ->
312 getModuleDs `thenDs` \ mod_name ->
313 returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
316 -- hdaume: core annotation
318 dsExpr (HsCoreAnn fs expr)
319 = dsLExpr expr `thenDs` \ core_expr ->
320 returnDs (Note (CoreNote $ unpackFS fs) core_expr)
322 dsExpr (HsCase discrim matches)
323 = dsLExpr discrim `thenDs` \ core_discrim ->
324 matchWrapper CaseAlt matches `thenDs` \ ([discrim_var], matching_code) ->
325 returnDs (scrungleMatch discrim_var core_discrim matching_code)
327 dsExpr (HsLet binds body)
328 = dsLExpr body `thenDs` \ body' ->
329 dsLocalBinds binds body'
331 -- We need the `ListComp' form to use `deListComp' (rather than the "do" form)
332 -- because the interpretation of `stmts' depends on what sort of thing it is.
334 dsExpr (HsDo ListComp stmts body result_ty)
335 = -- Special case for list comprehensions
336 dsListComp stmts body elt_ty
338 [elt_ty] = tcTyConAppArgs result_ty
340 dsExpr (HsDo DoExpr stmts body result_ty)
341 = dsDo stmts body result_ty
343 dsExpr (HsDo (MDoExpr tbl) stmts body result_ty)
344 = dsMDo tbl stmts body result_ty
346 dsExpr (HsDo PArrComp stmts body result_ty)
347 = -- Special case for array comprehensions
348 dsPArrComp (map unLoc stmts) body elt_ty
350 [elt_ty] = tcTyConAppArgs result_ty
352 dsExpr (HsIf guard_expr then_expr else_expr)
353 = dsLExpr guard_expr `thenDs` \ core_guard ->
354 dsLExpr then_expr `thenDs` \ core_then ->
355 dsLExpr else_expr `thenDs` \ core_else ->
356 returnDs (mkIfThenElse core_guard core_then core_else)
361 \underline{\bf Type lambda and application}
362 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~
364 dsExpr (TyLam tyvars expr)
365 = dsLExpr expr `thenDs` \ core_expr ->
366 returnDs (mkLams tyvars core_expr)
368 dsExpr (TyApp expr tys)
369 = dsLExpr expr `thenDs` \ core_expr ->
370 returnDs (mkTyApps core_expr tys)
375 \underline{\bf Various data construction things}
376 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
378 dsExpr (ExplicitList ty xs)
381 go [] = returnDs (mkNilExpr ty)
382 go (x:xs) = dsLExpr x `thenDs` \ core_x ->
383 go xs `thenDs` \ core_xs ->
384 returnDs (mkConsExpr ty core_x core_xs)
386 -- we create a list from the array elements and convert them into a list using
389 -- * the main disadvantage to this scheme is that `toP' traverses the list
390 -- twice: once to determine the length and a second time to put to elements
391 -- into the array; this inefficiency could be avoided by exposing some of
392 -- the innards of `PrelPArr' to the compiler (ie, have a `PrelPArrBase') so
393 -- that we can exploit the fact that we already know the length of the array
394 -- here at compile time
396 dsExpr (ExplicitPArr ty xs)
397 = dsLookupGlobalId toPName `thenDs` \toP ->
398 dsExpr (ExplicitList ty xs) `thenDs` \coreList ->
399 returnDs (mkApps (Var toP) [Type ty, coreList])
401 dsExpr (ExplicitTuple expr_list boxity)
402 = mappM dsLExpr expr_list `thenDs` \ core_exprs ->
403 returnDs (mkConApp (tupleCon boxity (length expr_list))
404 (map (Type . exprType) core_exprs ++ core_exprs))
406 dsExpr (ArithSeq expr (From from))
407 = dsExpr expr `thenDs` \ expr2 ->
408 dsLExpr from `thenDs` \ from2 ->
409 returnDs (App expr2 from2)
411 dsExpr (ArithSeq expr (FromTo from two))
412 = dsExpr expr `thenDs` \ expr2 ->
413 dsLExpr from `thenDs` \ from2 ->
414 dsLExpr two `thenDs` \ two2 ->
415 returnDs (mkApps expr2 [from2, two2])
417 dsExpr (ArithSeq expr (FromThen from thn))
418 = dsExpr expr `thenDs` \ expr2 ->
419 dsLExpr from `thenDs` \ from2 ->
420 dsLExpr thn `thenDs` \ thn2 ->
421 returnDs (mkApps expr2 [from2, thn2])
423 dsExpr (ArithSeq expr (FromThenTo from thn two))
424 = dsExpr expr `thenDs` \ expr2 ->
425 dsLExpr from `thenDs` \ from2 ->
426 dsLExpr thn `thenDs` \ thn2 ->
427 dsLExpr two `thenDs` \ two2 ->
428 returnDs (mkApps expr2 [from2, thn2, two2])
430 dsExpr (PArrSeq expr (FromTo from two))
431 = dsExpr expr `thenDs` \ expr2 ->
432 dsLExpr from `thenDs` \ from2 ->
433 dsLExpr two `thenDs` \ two2 ->
434 returnDs (mkApps expr2 [from2, two2])
436 dsExpr (PArrSeq expr (FromThenTo from thn two))
437 = dsExpr expr `thenDs` \ expr2 ->
438 dsLExpr from `thenDs` \ from2 ->
439 dsLExpr thn `thenDs` \ thn2 ->
440 dsLExpr two `thenDs` \ two2 ->
441 returnDs (mkApps expr2 [from2, thn2, two2])
443 dsExpr (PArrSeq expr _)
444 = panic "DsExpr.dsExpr: Infinite parallel array!"
445 -- the parser shouldn't have generated it and the renamer and typechecker
446 -- shouldn't have let it through
450 \underline{\bf Record construction and update}
451 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
452 For record construction we do this (assuming T has three arguments)
456 let err = /\a -> recConErr a
457 T (recConErr t1 "M.lhs/230/op1")
459 (recConErr t1 "M.lhs/230/op3")
461 @recConErr@ then converts its arugment string into a proper message
462 before printing it as
464 M.lhs, line 230: missing field op1 was evaluated
467 We also handle @C{}@ as valid construction syntax for an unlabelled
468 constructor @C@, setting all of @C@'s fields to bottom.
471 dsExpr (RecordCon (L _ data_con_id) con_expr rbinds)
472 = dsExpr con_expr `thenDs` \ con_expr' ->
474 (arg_tys, _) = tcSplitFunTys (exprType con_expr')
475 -- A newtype in the corner should be opaque;
476 -- hence TcType.tcSplitFunTys
478 mk_arg (arg_ty, lbl) -- Selector id has the field label as its name
479 = case [rhs | (L _ sel_id, rhs) <- rbinds, lbl == idName sel_id] of
480 (rhs:rhss) -> ASSERT( null rhss )
482 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
483 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
485 labels = dataConFieldLabels (idDataCon data_con_id)
486 -- The data_con_id is guaranteed to be the wrapper id of the constructor
490 then mappM unlabelled_bottom arg_tys
491 else mappM mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
492 `thenDs` \ con_args ->
494 returnDs (mkApps con_expr' con_args)
497 Record update is a little harder. Suppose we have the decl:
499 data T = T1 {op1, op2, op3 :: Int}
500 | T2 {op4, op2 :: Int}
503 Then we translate as follows:
509 T1 op1 _ op3 -> T1 op1 op2 op3
510 T2 op4 _ -> T2 op4 op2
511 other -> recUpdError "M.lhs/230"
513 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
514 RHSs, and do not generate a Core constructor application directly, because the constructor
515 might do some argument-evaluation first; and may have to throw away some
519 dsExpr (RecordUpd record_expr [] record_in_ty record_out_ty)
520 = dsLExpr record_expr
522 dsExpr expr@(RecordUpd record_expr rbinds record_in_ty record_out_ty)
523 = dsLExpr record_expr `thenDs` \ record_expr' ->
525 -- Desugar the rbinds, and generate let-bindings if
526 -- necessary so that we don't lose sharing
529 in_inst_tys = tcTyConAppArgs record_in_ty -- Newtype opaque
530 out_inst_tys = tcTyConAppArgs record_out_ty -- Newtype opaque
531 in_out_ty = mkFunTy record_in_ty record_out_ty
533 mk_val_arg field old_arg_id
534 = case [rhs | (L _ sel_id, rhs) <- rbinds, field == idName sel_id] of
535 (rhs:rest) -> ASSERT(null rest) rhs
536 [] -> nlHsVar old_arg_id
539 = newSysLocalsDs (dataConInstOrigArgTys con in_inst_tys) `thenDs` \ arg_ids ->
540 -- This call to dataConInstOrigArgTys won't work for existentials
541 -- but existentials don't have record types anyway
543 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
544 (dataConFieldLabels con) arg_ids
545 rhs = foldl (\a b -> nlHsApp a b)
546 (noLoc $ TyApp (nlHsVar (dataConWrapId con))
550 returnDs (mkSimpleMatch [noLoc $ ConPatOut (noLoc con) [] [] emptyLHsBinds
551 (PrefixCon (map nlVarPat arg_ids)) record_in_ty]
554 -- Record stuff doesn't work for existentials
555 -- The type checker checks for this, but we need
556 -- worry only about the constructors that are to be updated
557 ASSERT2( all isVanillaDataCon cons_to_upd, ppr expr )
559 -- It's important to generate the match with matchWrapper,
560 -- and the right hand sides with applications of the wrapper Id
561 -- so that everything works when we are doing fancy unboxing on the
562 -- constructor aguments.
563 mappM mk_alt cons_to_upd `thenDs` \ alts ->
564 matchWrapper RecUpd (MatchGroup alts in_out_ty) `thenDs` \ ([discrim_var], matching_code) ->
566 returnDs (bindNonRec discrim_var record_expr' matching_code)
569 updated_fields :: [FieldLabel]
570 updated_fields = [ idName sel_id | (L _ sel_id,_) <- rbinds]
572 -- Get the type constructor from the record_in_ty
573 -- so that we are sure it'll have all its DataCons
574 -- (In GHCI, it's possible that some TyCons may not have all
575 -- their constructors, in a module-loop situation.)
576 tycon = tcTyConAppTyCon record_in_ty
577 data_cons = tyConDataCons tycon
578 cons_to_upd = filter has_all_fields data_cons
580 has_all_fields :: DataCon -> Bool
581 has_all_fields con_id
582 = all (`elem` con_fields) updated_fields
584 con_fields = dataConFieldLabels con_id
589 \underline{\bf Dictionary lambda and application}
590 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
591 @DictLam@ and @DictApp@ turn into the regular old things.
592 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
593 complicated; reminiscent of fully-applied constructors.
595 dsExpr (DictLam dictvars expr)
596 = dsLExpr expr `thenDs` \ core_expr ->
597 returnDs (mkLams dictvars core_expr)
601 dsExpr (DictApp expr dicts) -- becomes a curried application
602 = dsLExpr expr `thenDs` \ core_expr ->
603 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
605 dsExpr (HsCoerce co_fn e) = dsCoercion co_fn (dsExpr e)
608 Here is where we desugar the Template Haskell brackets and escapes
611 -- Template Haskell stuff
613 #ifdef GHCI /* Only if bootstrapping */
614 dsExpr (HsBracketOut x ps) = dsBracket x ps
615 dsExpr (HsSpliceE s) = pprPanic "dsExpr:splice" (ppr s)
618 -- Arrow notation extension
619 dsExpr (HsProc pat cmd) = dsProcExpr pat cmd
626 -- HsSyn constructs that just shouldn't be here:
627 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
632 %--------------------------------------------------------------------
634 Desugar 'do' and 'mdo' expressions (NOT list comprehensions, they're
635 handled in DsListComp). Basically does the translation given in the
641 -> Type -- Type of the whole expression
644 dsDo stmts body result_ty
645 = go (map unLoc stmts)
649 go (ExprStmt rhs then_expr _ : stmts)
650 = do { rhs2 <- dsLExpr rhs
651 ; then_expr2 <- dsExpr then_expr
653 ; returnDs (mkApps then_expr2 [rhs2, rest]) }
655 go (LetStmt binds : stmts)
656 = do { rest <- go stmts
657 ; dsLocalBinds binds rest }
659 go (BindStmt pat rhs bind_op fail_op : stmts)
660 = do { body <- go stmts
661 ; var <- selectSimpleMatchVarL pat
662 ; match <- matchSinglePat (Var var) (StmtCtxt DoExpr) pat
663 result_ty (cantFailMatchResult body)
664 ; match_code <- handle_failure pat match fail_op
665 ; rhs' <- dsLExpr rhs
666 ; bind_op' <- dsExpr bind_op
667 ; returnDs (mkApps bind_op' [rhs', Lam var match_code]) }
669 -- In a do expression, pattern-match failure just calls
670 -- the monadic 'fail' rather than throwing an exception
671 handle_failure pat match fail_op
673 = do { fail_op' <- dsExpr fail_op
674 ; fail_msg <- mkStringExpr (mk_fail_msg pat)
675 ; extractMatchResult match (App fail_op' fail_msg) }
677 = extractMatchResult match (error "It can't fail")
679 mk_fail_msg pat = "Pattern match failure in do expression at " ++
680 showSDoc (ppr (getLoc pat))
683 Translation for RecStmt's:
684 -----------------------------
685 We turn (RecStmt [v1,..vn] stmts) into:
687 (v1,..,vn) <- mfix (\~(v1,..vn). do stmts
694 -> Type -- Type of the whole expression
697 dsMDo tbl stmts body result_ty
698 = go (map unLoc stmts)
700 (m_ty, b_ty) = tcSplitAppTy result_ty -- result_ty must be of the form (m b)
701 mfix_id = lookupEvidence tbl mfixName
702 return_id = lookupEvidence tbl returnMName
703 bind_id = lookupEvidence tbl bindMName
704 then_id = lookupEvidence tbl thenMName
705 fail_id = lookupEvidence tbl failMName
710 go (LetStmt binds : stmts)
711 = do { rest <- go stmts
712 ; dsLocalBinds binds rest }
714 go (ExprStmt rhs _ rhs_ty : stmts)
715 = do { rhs2 <- dsLExpr rhs
717 ; returnDs (mkApps (Var then_id) [Type rhs_ty, Type b_ty, rhs2, rest]) }
719 go (BindStmt pat rhs _ _ : stmts)
720 = do { body <- go stmts
721 ; var <- selectSimpleMatchVarL pat
722 ; match <- matchSinglePat (Var var) (StmtCtxt ctxt) pat
723 result_ty (cantFailMatchResult body)
724 ; fail_msg <- mkStringExpr (mk_fail_msg pat)
725 ; let fail_expr = mkApps (Var fail_id) [Type b_ty, fail_msg]
726 ; match_code <- extractMatchResult match fail_expr
728 ; rhs' <- dsLExpr rhs
729 ; returnDs (mkApps (Var bind_id) [Type (hsPatType pat), Type b_ty,
730 rhs', Lam var match_code]) }
732 go (RecStmt rec_stmts later_ids rec_ids rec_rets binds : stmts)
733 = ASSERT( length rec_ids > 0 )
734 ASSERT( length rec_ids == length rec_rets )
735 go (new_bind_stmt : let_stmt : stmts)
737 new_bind_stmt = mkBindStmt (mk_tup_pat later_pats) mfix_app
738 let_stmt = LetStmt (HsValBinds (ValBindsOut [(Recursive, binds)] []))
741 -- Remove the later_ids that appear (without fancy coercions)
742 -- in rec_rets, because there's no need to knot-tie them separately
743 -- See Note [RecStmt] in HsExpr
744 later_ids' = filter (`notElem` mono_rec_ids) later_ids
745 mono_rec_ids = [ id | HsVar id <- rec_rets ]
747 mfix_app = nlHsApp (noLoc $ TyApp (nlHsVar mfix_id) [tup_ty]) mfix_arg
748 mfix_arg = noLoc $ HsLam (MatchGroup [mkSimpleMatch [mfix_pat] body]
749 (mkFunTy tup_ty body_ty))
751 -- The rec_tup_pat must bind the rec_ids only; remember that the
752 -- trimmed_laters may share the same Names
753 -- Meanwhile, the later_pats must bind the later_vars
754 rec_tup_pats = map mk_wild_pat later_ids' ++ map nlVarPat rec_ids
755 later_pats = map nlVarPat later_ids' ++ map mk_later_pat rec_ids
756 rets = map nlHsVar later_ids' ++ map noLoc rec_rets
758 mfix_pat = noLoc $ LazyPat $ mk_tup_pat rec_tup_pats
759 body = noLoc $ HsDo ctxt rec_stmts return_app body_ty
760 body_ty = mkAppTy m_ty tup_ty
761 tup_ty = mkCoreTupTy (map idType (later_ids' ++ rec_ids))
762 -- mkCoreTupTy deals with singleton case
764 return_app = nlHsApp (noLoc $ TyApp (nlHsVar return_id) [tup_ty])
767 mk_wild_pat :: Id -> LPat Id
768 mk_wild_pat v = noLoc $ WildPat $ idType v
770 mk_later_pat :: Id -> LPat Id
771 mk_later_pat v | v `elem` later_ids' = mk_wild_pat v
772 | otherwise = nlVarPat v
774 mk_tup_pat :: [LPat Id] -> LPat Id
776 mk_tup_pat ps = noLoc $ mkVanillaTuplePat ps Boxed
778 mk_ret_tup :: [LHsExpr Id] -> LHsExpr Id
780 mk_ret_tup rs = noLoc $ ExplicitTuple rs Boxed