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 (Note (Coerce (idType arg_id) scrut_ty) (Var var))
205 newtype_sanity = null (tail alts) && null (tail arg_ids)
207 -- Stuff for data types
208 data_cons = tyConDataCons tycon
210 un_mentioned_constructors
211 = uniqSetToList (mkUniqSet data_cons `minusUniqSet` mkUniqSet [ con | (con, _, _) <- alts] )
213 match_results = [match_result | (_,_,match_result) <- alts]
214 (MatchResult _ ty1 _ : _) = match_results
215 can_any_alt_fail = foldr1 orFail [can_it_fail | MatchResult can_it_fail _ _ <- match_results]
217 mk_case alts deflt_fn fail_expr
218 = Case (Var var) (AlgAlts final_alts (deflt_fn fail_expr))
220 final_alts = [ (con, args, body_fn fail_expr)
221 | (con, args, MatchResult _ _ body_fn) <- alts
225 combineMatchResults :: MatchResult -> MatchResult -> DsM MatchResult
226 combineMatchResults (MatchResult CanFail ty1 body_fn1)
227 (MatchResult can_it_fail2 ty2 body_fn2)
228 = mkFailurePair ty1 `thenDs` \ (bind_fn, duplicatable_expr) ->
230 new_body_fn1 = \body1 -> Let (bind_fn body1) (body_fn1 duplicatable_expr)
231 new_body_fn2 = \body2 -> new_body_fn1 (body_fn2 body2)
233 returnDs (MatchResult can_it_fail2 ty1 new_body_fn2)
235 combineMatchResults match_result1@(MatchResult CantFail ty body_fn1)
237 = returnDs match_result1
240 -- The difference in combineGRHSMatchResults is that there is no
241 -- need to let-bind to avoid code duplication
242 combineGRHSMatchResults :: MatchResult -> MatchResult -> DsM MatchResult
243 combineGRHSMatchResults (MatchResult CanFail ty1 body_fn1)
244 (MatchResult can_it_fail ty2 body_fn2)
245 = returnDs (MatchResult can_it_fail ty1 (\ body -> body_fn1 (body_fn2 body)))
247 combineGRHSMatchResults match_result1 match_result2
248 = -- Delegate to avoid duplication of code
249 combineMatchResults match_result1 match_result2
252 %************************************************************************
254 \subsection[dsExprToAtom]{Take an expression and produce an atom}
256 %************************************************************************
259 dsArgToAtom :: DsCoreArg -- The argument expression
260 -> (CoreArg -> DsM CoreExpr) -- Something taking the argument *atom*,
261 -- and delivering an expression E
262 -> DsM CoreExpr -- Either E or let x=arg-expr in E
264 dsArgToAtom (TyArg t) continue_with = continue_with (TyArg t)
265 dsArgToAtom (LitArg l) continue_with = continue_with (LitArg l)
266 dsArgToAtom (VarArg arg) continue_with = dsExprToAtomGivenTy arg (coreExprType arg) continue_with
269 :: CoreExpr -- The argument expression
270 -> Type -- Type of the argument
271 -> (CoreArg -> DsM CoreExpr) -- Something taking the argument *atom*,
272 -- and delivering an expression E
273 -> DsM CoreExpr -- Either E or let x=arg-expr in E
275 dsExprToAtomGivenTy (Var v) arg_ty continue_with = continue_with (VarArg v)
276 dsExprToAtomGivenTy (Lit v) arg_ty continue_with = continue_with (LitArg v)
277 dsExprToAtomGivenTy arg_expr arg_ty continue_with
278 = newSysLocalDs arg_ty `thenDs` \ arg_id ->
279 continue_with (VarArg arg_id) `thenDs` \ body ->
281 if isUnpointedType arg_ty
282 then Case arg_expr (PrimAlts [] (BindDefault arg_id body))
283 else Let (NonRec arg_id arg_expr) body
286 dsArgsToAtoms :: [DsCoreArg]
287 -> ([CoreArg] -> DsM CoreExpr)
290 dsArgsToAtoms [] continue_with = continue_with []
292 dsArgsToAtoms (arg:args) continue_with
293 = dsArgToAtom arg $ \ arg_atom ->
294 dsArgsToAtoms args $ \ arg_atoms ->
295 continue_with (arg_atom:arg_atoms)
298 %************************************************************************
300 \subsection{Desugarer's versions of some Core functions}
302 %************************************************************************
305 type DsCoreArg = GenCoreArg CoreExpr{-NB!-} Unused
307 mkAppDs :: CoreExpr -> [DsCoreArg] -> DsM CoreExpr
308 mkConDs :: Id -> [DsCoreArg] -> DsM CoreExpr
309 mkPrimDs :: PrimOp -> [DsCoreArg] -> DsM CoreExpr
312 = dsArgsToAtoms args $ \ atoms ->
313 returnDs (mkGenApp fun atoms)
316 = dsArgsToAtoms args $ \ atoms ->
317 returnDs (Con con atoms)
320 = dsArgsToAtoms args $ \ atoms ->
321 returnDs (Prim op atoms)
325 showForErr :: Outputable a => a -> String -- Boring but useful
326 showForErr thing = showSDoc (ppr thing)
328 mkErrorAppDs :: Id -- The error function
329 -> Type -- Type to which it should be applied
330 -> String -- The error message string to pass
333 mkErrorAppDs err_id ty msg
334 = getSrcLocDs `thenDs` \ src_loc ->
336 full_msg = showSDoc (hcat [ppr src_loc, text "|", text msg])
337 msg_lit = NoRepStr (_PK_ full_msg)
339 returnDs (mkApp (Var err_id) [ty] [LitArg msg_lit])
342 %************************************************************************
344 \subsection[mkSelectorBind]{Make a selector bind}
346 %************************************************************************
348 This is used in various places to do with lazy patterns.
349 For each binder $b$ in the pattern, we create a binding:
351 b = case v of pat' -> b'
353 where pat' is pat with each binder b cloned into b'.
355 ToDo: making these bindings should really depend on whether there's
356 much work to be done per binding. If the pattern is complex, it
357 should be de-mangled once, into a tuple (and then selected from).
358 Otherwise the demangling can be in-line in the bindings (as here).
360 Boring! Boring! One error message per binder. The above ToDo is
361 even more helpful. Something very similar happens for pattern-bound
365 mkSelectorBinds :: TypecheckedPat -- The pattern
366 -> CoreExpr -- Expression to which the pattern is bound
367 -> DsM [(Id,CoreExpr)]
369 mkSelectorBinds (VarPat v) val_expr
370 = returnDs [(v, val_expr)]
372 mkSelectorBinds pat val_expr
373 | length binders == 1 || is_simple_pat pat
374 = newSysLocalDs (coreExprType val_expr) `thenDs` \ val_var ->
376 -- For the error message we don't use mkErrorAppDs to avoid
377 -- duplicating the string literal each time
378 newSysLocalDs stringTy `thenDs` \ msg_var ->
379 getSrcLocDs `thenDs` \ src_loc ->
381 full_msg = showSDoc (hcat [ppr src_loc, text "|", ppr pat])
382 msg_lit = NoRepStr (_PK_ full_msg)
384 mapDs (mk_bind val_var msg_var) binders `thenDs` \ binds ->
385 returnDs ( (val_var, val_expr) :
386 (msg_var, Lit msg_lit) :
391 = mkErrorAppDs iRREFUT_PAT_ERROR_ID tuple_ty (showSDoc (ppr pat)) `thenDs` \ error_expr ->
392 matchSimply val_expr LetMatch pat tuple_ty local_tuple error_expr `thenDs` \ tuple_expr ->
393 newSysLocalDs tuple_ty `thenDs` \ tuple_var ->
395 mk_tup_bind binder = (binder, mkTupleSelector binders binder (Var tuple_var))
397 returnDs ( (tuple_var, tuple_expr) : map mk_tup_bind binders )
399 binders = collectTypedPatBinders pat
400 local_tuple = mkTupleExpr binders
401 tuple_ty = coreExprType local_tuple
403 mk_bind scrut_var msg_var bndr_var
404 -- (mk_bind sv bv) generates
405 -- bv = case sv of { pat -> bv; other -> error-msg }
406 -- Remember, pat binds bv
407 = matchSimply (Var scrut_var) LetMatch pat binder_ty
408 (Var bndr_var) error_expr `thenDs` \ rhs_expr ->
409 returnDs (bndr_var, rhs_expr)
411 binder_ty = idType bndr_var
412 error_expr = mkApp (Var iRREFUT_PAT_ERROR_ID) [binder_ty] [VarArg msg_var]
414 is_simple_pat (TuplePat ps) = all is_triv_pat ps
415 is_simple_pat (ConPat _ _ ps) = all is_triv_pat ps
416 is_simple_pat (VarPat _) = True
417 is_simple_pat (ConOpPat p1 _ p2 _) = is_triv_pat p1 && is_triv_pat p2
418 is_simple_pat (RecPat _ _ ps) = and [is_triv_pat p | (_,p,_) <- ps]
419 is_simple_pat other = False
421 is_triv_pat (VarPat v) = True
422 is_triv_pat (WildPat _) = True
423 is_triv_pat other = False
427 @mkTupleExpr@ builds a tuple; the inverse to @mkTupleSelector@. If it
428 has only one element, it is the identity function.
431 mkTupleExpr :: [Id] -> CoreExpr
433 mkTupleExpr [] = Con unitDataCon []
434 mkTupleExpr [id] = Var id
435 mkTupleExpr ids = mkCon (tupleCon (length ids))
437 [ VarArg i | i <- ids ]
441 @mkTupleSelector@ builds a selector which scrutises the given
442 expression and extracts the one name from the list given.
443 If you want the no-shadowing rule to apply, the caller
444 is responsible for making sure that none of these names
447 If there is just one id in the ``tuple'', then the selector is
451 mkTupleSelector :: [Id] -- The tuple args
452 -> Id -- The selected one
453 -> CoreExpr -- Scrutinee
456 mkTupleSelector [var] should_be_the_same_var scrut
457 = ASSERT(var == should_be_the_same_var)
460 mkTupleSelector vars the_var scrut
461 = ASSERT( not (null vars) )
462 Case scrut (AlgAlts [(tupleCon (length vars), vars, Var the_var)] NoDefault)
466 %************************************************************************
468 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
470 %************************************************************************
472 Generally, we handle pattern matching failure like this: let-bind a
473 fail-variable, and use that variable if the thing fails:
475 let fail.33 = error "Help"
486 If the case can't fail, then there'll be no mention of fail.33, and the
487 simplifier will later discard it.
490 If it can fail in only one way, then the simplifier will inline it.
493 Only if it is used more than once will the let-binding remain.
496 There's a problem when the result of the case expression is of
497 unboxed type. Then the type of fail.33 is unboxed too, and
498 there is every chance that someone will change the let into a case:
504 which is of course utterly wrong. Rather than drop the condition that
505 only boxed types can be let-bound, we just turn the fail into a function
506 for the primitive case:
508 let fail.33 :: Void -> Int#
509 fail.33 = \_ -> error "Help"
518 Now fail.33 is a function, so it can be let-bound.
521 mkFailurePair :: Type -- Result type of the whole case expression
522 -> DsM (CoreExpr -> CoreBinding,
523 -- Binds the newly-created fail variable
524 -- to either the expression or \ _ -> expression
525 CoreExpr) -- Either the fail variable, or fail variable
526 -- applied to unit tuple
529 = newFailLocalDs (voidTy `mkFunTy` ty) `thenDs` \ fail_fun_var ->
530 newSysLocalDs voidTy `thenDs` \ fail_fun_arg ->
532 NonRec fail_fun_var (Lam (ValBinder fail_fun_arg) body),
533 App (Var fail_fun_var) (VarArg voidId))
536 = newFailLocalDs ty `thenDs` \ fail_var ->
537 returnDs (\ body -> NonRec fail_var body, Var fail_var)