2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[DsUtils]{Utilities for desugaring}
6 This module exports some utility functions of no great interest.
10 CanItFail(..), EquationInfo(..), MatchResult(..),
13 combineGRHSMatchResults,
15 dsExprToAtomGivenTy, DsCoreArg,
16 mkCoAlgCaseMatchResult,
17 mkAppDs, mkConDs, mkPrimDs, mkErrorAppDs,
19 mkCoPrimCaseMatchResult,
29 #include "HsVersions.h"
31 import {-# SOURCE #-} Match ( matchSimply )
33 import HsSyn ( OutPat(..), Stmt, DoOrListComp )
34 import TcHsSyn ( TypecheckedPat )
35 import DsHsSyn ( outPatType, collectTypedPatBinders )
40 import CoreUtils ( coreExprType, mkCoreIfThenElse )
41 import PrelVals ( iRREFUT_PAT_ERROR_ID, voidId )
42 import Id ( idType, dataConArgTys,
44 import Literal ( Literal(..) )
45 import PrimOp ( PrimOp )
46 import TyCon ( isNewTyCon, tyConDataCons )
47 import Type ( mkRhoTy, mkFunTy,
48 isUnpointedType, mkTyConApp, splitAlgTyConApp,
51 import BasicTypes ( Unused )
52 import TysPrim ( voidTy )
53 import TysWiredIn ( unitDataCon, tupleCon, stringTy )
54 import UniqSet ( mkUniqSet, minusUniqSet, uniqSetToList, UniqSet )
55 import Unique ( Unique )
60 %************************************************************************
62 %* Selecting match variables
64 %************************************************************************
66 We're about to match against some patterns. We want to make some
67 @Ids@ to use as match variables. If a pattern has an @Id@ readily at
68 hand, which should indeed be bound to the pattern as a whole, then use it;
69 otherwise, make one up.
72 selectMatchVars :: [TypecheckedPat] -> DsM [Id]
74 = mapDs var_from_pat_maybe pats
76 var_from_pat_maybe (VarPat var) = returnDs var
77 var_from_pat_maybe (AsPat var pat) = returnDs var
78 var_from_pat_maybe (LazyPat pat) = var_from_pat_maybe pat
79 var_from_pat_maybe other_pat
80 = newSysLocalDs (outPatType other_pat) -- OK, better make up one...
84 %************************************************************************
86 %* type synonym EquationInfo and access functions for its pieces *
88 %************************************************************************
89 \subsection[EquationInfo-synonym]{@EquationInfo@: a useful synonym}
91 The ``equation info'' used by @match@ is relatively complicated and
92 worthy of a type synonym and a few handy functions.
97 type EqnSet = UniqSet EqnNo
101 EqnNo -- The number of the equation
102 DsMatchContext -- The context info is used when producing warnings
103 -- about shadowed patterns. It's the context
104 -- of the *first* thing matched in this group.
105 -- Should perhaps be a list of them all!
106 [TypecheckedPat] -- the patterns for an eqn
107 MatchResult -- Encapsulates the guards and bindings
114 Type -- Type of argument expression
116 (CoreExpr -> CoreExpr)
117 -- Takes a expression to plug in at the
118 -- failure point(s). The expression should
121 data CanItFail = CanFail | CantFail
123 orFail CantFail CantFail = CantFail
127 mkCoLetsMatchResult :: [CoreBinding] -> MatchResult -> MatchResult
128 mkCoLetsMatchResult binds (MatchResult can_it_fail ty body_fn)
129 = MatchResult can_it_fail ty (\body -> mkCoLetsAny binds (body_fn body))
131 mkGuardedMatchResult :: CoreExpr -> MatchResult -> DsM MatchResult
132 mkGuardedMatchResult pred_expr (MatchResult can_it_fail ty body_fn)
133 = returnDs (MatchResult CanFail
135 (\fail -> mkCoreIfThenElse pred_expr (body_fn fail) fail)
138 mkCoPrimCaseMatchResult :: Id -- Scrutinee
139 -> [(Literal, MatchResult)] -- Alternatives
141 mkCoPrimCaseMatchResult var alts
142 = newSysLocalDs (idType var) `thenDs` \ wild ->
143 returnDs (MatchResult CanFail
147 ((_,MatchResult _ ty1 _) : _) = alts
149 mk_case alts wild fail_expr
150 = Case (Var var) (PrimAlts final_alts (BindDefault wild fail_expr))
152 final_alts = [ (lit, body_fn fail_expr)
153 | (lit, MatchResult _ _ body_fn) <- alts
157 mkCoAlgCaseMatchResult :: Id -- Scrutinee
158 -> [(DataCon, [Id], MatchResult)] -- Alternatives
161 mkCoAlgCaseMatchResult var alts
162 | isNewTyCon tycon -- newtype case; use a let
163 = ASSERT( newtype_sanity )
164 returnDs (mkCoLetsMatchResult [coercion_bind] match_result)
166 | otherwise -- datatype case
167 = -- Find all the constructors in the type which aren't
168 -- explicitly mentioned in the alternatives:
169 case un_mentioned_constructors of
170 [] -> -- All constructors mentioned, so no default needed
171 returnDs (MatchResult can_any_alt_fail
173 (mk_case alts (\ignore -> NoDefault)))
175 [con] -> -- Just one constructor missing, so add a case for it
176 -- We need to build new locals for the args of the constructor,
177 -- and figuring out their types is somewhat tiresome.
179 arg_tys = dataConArgTys con tycon_arg_tys
181 newSysLocalsDs arg_tys `thenDs` \ arg_ids ->
183 -- Now we are ready to construct the new alternative
185 new_alt = (con, arg_ids, MatchResult CanFail ty1 id)
187 returnDs (MatchResult CanFail
189 (mk_case (new_alt:alts) (\ignore -> NoDefault)))
191 other -> -- Many constructors missing, so use a default case
192 newSysLocalDs scrut_ty `thenDs` \ wild ->
193 returnDs (MatchResult CanFail
195 (mk_case alts (\fail_expr -> BindDefault wild fail_expr)))
198 scrut_ty = idType var
199 (tycon, tycon_arg_tys, _) = splitAlgTyConApp scrut_ty
202 (con_id, arg_ids, match_result) = head alts
203 arg_id = head arg_ids
204 coercion_bind = NonRec arg_id (Coerce (CoerceOut con_id)
207 newtype_sanity = null (tail alts) && null (tail arg_ids)
209 -- Stuff for data types
210 data_cons = tyConDataCons tycon
212 un_mentioned_constructors
213 = uniqSetToList (mkUniqSet data_cons `minusUniqSet` mkUniqSet [ con | (con, _, _) <- alts] )
215 match_results = [match_result | (_,_,match_result) <- alts]
216 (MatchResult _ ty1 _ : _) = match_results
217 can_any_alt_fail = foldr1 orFail [can_it_fail | MatchResult can_it_fail _ _ <- match_results]
219 mk_case alts deflt_fn fail_expr
220 = Case (Var var) (AlgAlts final_alts (deflt_fn fail_expr))
222 final_alts = [ (con, args, body_fn fail_expr)
223 | (con, args, MatchResult _ _ body_fn) <- alts
227 combineMatchResults :: MatchResult -> MatchResult -> DsM MatchResult
228 combineMatchResults (MatchResult CanFail ty1 body_fn1)
229 (MatchResult can_it_fail2 ty2 body_fn2)
230 = mkFailurePair ty1 `thenDs` \ (bind_fn, duplicatable_expr) ->
232 new_body_fn1 = \body1 -> Let (bind_fn body1) (body_fn1 duplicatable_expr)
233 new_body_fn2 = \body2 -> new_body_fn1 (body_fn2 body2)
235 returnDs (MatchResult can_it_fail2 ty1 new_body_fn2)
237 combineMatchResults match_result1@(MatchResult CantFail ty body_fn1)
239 = returnDs match_result1
242 -- The difference in combineGRHSMatchResults is that there is no
243 -- need to let-bind to avoid code duplication
244 combineGRHSMatchResults :: MatchResult -> MatchResult -> DsM MatchResult
245 combineGRHSMatchResults (MatchResult CanFail ty1 body_fn1)
246 (MatchResult can_it_fail ty2 body_fn2)
247 = returnDs (MatchResult can_it_fail ty1 (\ body -> body_fn1 (body_fn2 body)))
249 combineGRHSMatchResults match_result1 match_result2
250 = -- Delegate to avoid duplication of code
251 combineMatchResults match_result1 match_result2
254 %************************************************************************
256 \subsection[dsExprToAtom]{Take an expression and produce an atom}
258 %************************************************************************
261 dsArgToAtom :: DsCoreArg -- The argument expression
262 -> (CoreArg -> DsM CoreExpr) -- Something taking the argument *atom*,
263 -- and delivering an expression E
264 -> DsM CoreExpr -- Either E or let x=arg-expr in E
266 dsArgToAtom (TyArg t) continue_with = continue_with (TyArg t)
267 dsArgToAtom (LitArg l) continue_with = continue_with (LitArg l)
268 dsArgToAtom (VarArg arg) continue_with = dsExprToAtomGivenTy arg (coreExprType arg) continue_with
271 :: CoreExpr -- The argument expression
272 -> Type -- Type of the argument
273 -> (CoreArg -> DsM CoreExpr) -- Something taking the argument *atom*,
274 -- and delivering an expression E
275 -> DsM CoreExpr -- Either E or let x=arg-expr in E
277 dsExprToAtomGivenTy (Var v) arg_ty continue_with = continue_with (VarArg v)
278 dsExprToAtomGivenTy (Lit v) arg_ty continue_with = continue_with (LitArg v)
279 dsExprToAtomGivenTy arg_expr arg_ty continue_with
280 = newSysLocalDs arg_ty `thenDs` \ arg_id ->
281 continue_with (VarArg arg_id) `thenDs` \ body ->
283 if isUnpointedType arg_ty
284 then Case arg_expr (PrimAlts [] (BindDefault arg_id body))
285 else Let (NonRec arg_id arg_expr) body
288 dsArgsToAtoms :: [DsCoreArg]
289 -> ([CoreArg] -> DsM CoreExpr)
292 dsArgsToAtoms [] continue_with = continue_with []
294 dsArgsToAtoms (arg:args) continue_with
295 = dsArgToAtom arg $ \ arg_atom ->
296 dsArgsToAtoms args $ \ arg_atoms ->
297 continue_with (arg_atom:arg_atoms)
300 %************************************************************************
302 \subsection{Desugarer's versions of some Core functions}
304 %************************************************************************
307 type DsCoreArg = GenCoreArg CoreExpr{-NB!-} Unused
309 mkAppDs :: CoreExpr -> [DsCoreArg] -> DsM CoreExpr
310 mkConDs :: Id -> [DsCoreArg] -> DsM CoreExpr
311 mkPrimDs :: PrimOp -> [DsCoreArg] -> DsM CoreExpr
314 = dsArgsToAtoms args $ \ atoms ->
315 returnDs (mkGenApp fun atoms)
318 = dsArgsToAtoms args $ \ atoms ->
319 returnDs (Con con atoms)
322 = dsArgsToAtoms args $ \ atoms ->
323 returnDs (Prim op atoms)
327 showForErr :: Outputable a => a -> String -- Boring but useful
328 showForErr thing = showSDoc (ppr thing)
330 mkErrorAppDs :: Id -- The error function
331 -> Type -- Type to which it should be applied
332 -> String -- The error message string to pass
335 mkErrorAppDs err_id ty msg
336 = getSrcLocDs `thenDs` \ src_loc ->
338 full_msg = showSDoc (hcat [ppr src_loc, text "|", text msg])
339 msg_lit = NoRepStr (_PK_ full_msg)
341 returnDs (mkApp (Var err_id) [ty] [LitArg msg_lit])
344 %************************************************************************
346 \subsection[mkSelectorBind]{Make a selector bind}
348 %************************************************************************
350 This is used in various places to do with lazy patterns.
351 For each binder $b$ in the pattern, we create a binding:
353 b = case v of pat' -> b'
355 where pat' is pat with each binder b cloned into b'.
357 ToDo: making these bindings should really depend on whether there's
358 much work to be done per binding. If the pattern is complex, it
359 should be de-mangled once, into a tuple (and then selected from).
360 Otherwise the demangling can be in-line in the bindings (as here).
362 Boring! Boring! One error message per binder. The above ToDo is
363 even more helpful. Something very similar happens for pattern-bound
367 mkSelectorBinds :: TypecheckedPat -- The pattern
368 -> CoreExpr -- Expression to which the pattern is bound
369 -> DsM [(Id,CoreExpr)]
371 mkSelectorBinds (VarPat v) val_expr
372 = returnDs [(v, val_expr)]
374 mkSelectorBinds pat val_expr
375 | length binders == 1 || is_simple_pat pat
376 = newSysLocalDs (coreExprType val_expr) `thenDs` \ val_var ->
378 -- For the error message we don't use mkErrorAppDs to avoid
379 -- duplicating the string literal each time
380 newSysLocalDs stringTy `thenDs` \ msg_var ->
381 getSrcLocDs `thenDs` \ src_loc ->
383 full_msg = showSDoc (hcat [ppr src_loc, text "|", ppr pat])
384 msg_lit = NoRepStr (_PK_ full_msg)
386 mapDs (mk_bind val_var msg_var) binders `thenDs` \ binds ->
387 returnDs ( (val_var, val_expr) :
388 (msg_var, Lit msg_lit) :
393 = mkErrorAppDs iRREFUT_PAT_ERROR_ID tuple_ty (showSDoc (ppr pat)) `thenDs` \ error_expr ->
394 matchSimply val_expr LetMatch pat tuple_ty local_tuple error_expr `thenDs` \ tuple_expr ->
395 newSysLocalDs tuple_ty `thenDs` \ tuple_var ->
397 mk_tup_bind binder = (binder, mkTupleSelector binders binder (Var tuple_var))
399 returnDs ( (tuple_var, tuple_expr) : map mk_tup_bind binders )
401 binders = collectTypedPatBinders pat
402 local_tuple = mkTupleExpr binders
403 tuple_ty = coreExprType local_tuple
405 mk_bind scrut_var msg_var bndr_var
406 -- (mk_bind sv bv) generates
407 -- bv = case sv of { pat -> bv; other -> error-msg }
408 -- Remember, pat binds bv
409 = matchSimply (Var scrut_var) LetMatch pat binder_ty
410 (Var bndr_var) error_expr `thenDs` \ rhs_expr ->
411 returnDs (bndr_var, rhs_expr)
413 binder_ty = idType bndr_var
414 error_expr = mkApp (Var iRREFUT_PAT_ERROR_ID) [binder_ty] [VarArg msg_var]
416 is_simple_pat (TuplePat ps) = all is_triv_pat ps
417 is_simple_pat (ConPat _ _ ps) = all is_triv_pat ps
418 is_simple_pat (VarPat _) = True
419 is_simple_pat (ConOpPat p1 _ p2 _) = is_triv_pat p1 && is_triv_pat p2
420 is_simple_pat (RecPat _ _ ps) = and [is_triv_pat p | (_,p,_) <- ps]
421 is_simple_pat other = False
423 is_triv_pat (VarPat v) = True
424 is_triv_pat (WildPat _) = True
425 is_triv_pat other = False
429 @mkTupleExpr@ builds a tuple; the inverse to @mkTupleSelector@. If it
430 has only one element, it is the identity function.
433 mkTupleExpr :: [Id] -> CoreExpr
435 mkTupleExpr [] = Con unitDataCon []
436 mkTupleExpr [id] = Var id
437 mkTupleExpr ids = mkCon (tupleCon (length ids))
439 [ VarArg i | i <- ids ]
443 @mkTupleSelector@ builds a selector which scrutises the given
444 expression and extracts the one name from the list given.
445 If you want the no-shadowing rule to apply, the caller
446 is responsible for making sure that none of these names
449 If there is just one id in the ``tuple'', then the selector is
453 mkTupleSelector :: [Id] -- The tuple args
454 -> Id -- The selected one
455 -> CoreExpr -- Scrutinee
458 mkTupleSelector [var] should_be_the_same_var scrut
459 = ASSERT(var == should_be_the_same_var)
462 mkTupleSelector vars the_var scrut
463 = ASSERT( not (null vars) )
464 Case scrut (AlgAlts [(tupleCon (length vars), vars, Var the_var)] NoDefault)
468 %************************************************************************
470 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
472 %************************************************************************
474 Generally, we handle pattern matching failure like this: let-bind a
475 fail-variable, and use that variable if the thing fails:
477 let fail.33 = error "Help"
488 If the case can't fail, then there'll be no mention of fail.33, and the
489 simplifier will later discard it.
492 If it can fail in only one way, then the simplifier will inline it.
495 Only if it is used more than once will the let-binding remain.
498 There's a problem when the result of the case expression is of
499 unboxed type. Then the type of fail.33 is unboxed too, and
500 there is every chance that someone will change the let into a case:
506 which is of course utterly wrong. Rather than drop the condition that
507 only boxed types can be let-bound, we just turn the fail into a function
508 for the primitive case:
510 let fail.33 :: Void -> Int#
511 fail.33 = \_ -> error "Help"
520 Now fail.33 is a function, so it can be let-bound.
523 mkFailurePair :: Type -- Result type of the whole case expression
524 -> DsM (CoreExpr -> CoreBinding,
525 -- Binds the newly-created fail variable
526 -- to either the expression or \ _ -> expression
527 CoreExpr) -- Either the fail variable, or fail variable
528 -- applied to unit tuple
531 = newFailLocalDs (voidTy `mkFunTy` ty) `thenDs` \ fail_fun_var ->
532 newSysLocalDs voidTy `thenDs` \ fail_fun_arg ->
534 NonRec fail_fun_var (Lam (ValBinder fail_fun_arg) body),
535 App (Var fail_fun_var) (VarArg voidId))
538 = newFailLocalDs ty `thenDs` \ fail_var ->
539 returnDs (\ body -> NonRec fail_var body, Var fail_var)