2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1995
4 \section[DsUtils]{Utilities for desugaring}
6 This module exports some utility functions of no great interest.
9 #include "HsVersions.h"
12 CanItFail(..), EquationInfo(..), MatchResult(..),
14 combineGRHSMatchResults,
17 mkCoAlgCaseMatchResult,
21 mkCoPrimCaseMatchResult,
31 import AbsSyn -- the stuff being desugared
32 import PlainCore -- the output of desugaring;
33 -- importing this module also gets all the
34 -- CoreSyn utility functions
35 import DsMonad -- the monadery used in the desugarer
37 import AbsPrel ( mkFunTy, stringTy
38 IF_ATTACK_PRAGMAS(COMMA mkListTy COMMA charTy)
40 import AbsUniType ( mkTyVarTy, quantifyTy, mkTupleTyCon,
41 mkRhoTy, splitDictType, applyTyCon,
42 getUniDataTyCon, isUnboxedDataType,
43 TyVar, TyVarTemplate, TyCon, Arity(..), Class,
44 UniType, RhoType(..), SigmaType(..)
46 import Id ( getIdUniType, getInstantiatedDataConSig,
47 mkTupleCon, DataCon(..), Id
49 import Maybes ( Maybe(..) )
50 import Match ( match, matchSimply )
52 import Unique ( initUs, UniqueSupply, UniqSM(..) )
57 %************************************************************************
59 %* type synonym EquationInfo and access functions for its pieces *
61 %************************************************************************
62 \subsection[EquationInfo-synonym]{@EquationInfo@: a useful synonym}
64 The ``equation info'' used by @match@ is relatively complicated and
65 worthy of a type synonym and a few handy functions.
70 [TypecheckedPat] -- the patterns for an eqn
71 MatchResult -- Encapsulates the guards and bindings
78 UniType -- Type of argument expression
80 (PlainCoreExpr -> PlainCoreExpr)
81 -- Takes a expression to plug in at the
82 -- failure point(s). The expression should
85 DsMatchContext -- The context info is used when producing warnings
86 -- about shadowed patterns. It's the context
87 -- of the *first* thing matched in this group.
88 -- Should perhaps be a list of them all!
90 data CanItFail = CanFail | CantFail
92 orFail CantFail CantFail = CantFail
96 mkCoLetsMatchResult :: [PlainCoreBinding] -> MatchResult -> MatchResult
97 mkCoLetsMatchResult binds (MatchResult can_it_fail ty body_fn cxt)
98 = MatchResult can_it_fail ty (\body -> mkCoLetsAny binds (body_fn body)) cxt
100 mkGuardedMatchResult :: PlainCoreExpr -> MatchResult -> DsM MatchResult
101 mkGuardedMatchResult pred_expr (MatchResult can_it_fail ty body_fn cxt)
102 = returnDs (MatchResult CanFail
104 (\fail -> mkCoreIfThenElse pred_expr (body_fn fail) fail)
108 mkCoPrimCaseMatchResult :: Id -- Scrutinee
109 -> [(BasicLit, MatchResult)] -- Alternatives
111 mkCoPrimCaseMatchResult var alts
112 = newSysLocalDs (getIdUniType var) `thenDs` \ wild ->
113 returnDs (MatchResult CanFail
118 ((_,MatchResult _ ty1 _ cxt1) : _) = alts
120 mk_case alts wild fail_expr
121 = CoCase (CoVar var) (CoPrimAlts final_alts (CoBindDefault wild fail_expr))
123 final_alts = [ (lit, body_fn fail_expr)
124 | (lit, MatchResult _ _ body_fn _) <- alts
128 mkCoAlgCaseMatchResult :: Id -- Scrutinee
129 -> [(DataCon, [Id], MatchResult)] -- Alternatives
131 mkCoAlgCaseMatchResult var alts
132 = -- Find all the constructors in the type which aren't
133 -- explicitly mentioned in the alternatives:
134 case un_mentioned_constructors of
135 [] -> -- All constructors mentioned, so no default needed
136 returnDs (MatchResult can_any_alt_fail
138 (mk_case alts (\ignore -> CoNoDefault))
141 [con] -> -- Just one constructor missing, so add a case for it
142 -- We need to build new locals for the args of the constructor,
143 -- and figuring out their types is somewhat tiresome.
145 (_,arg_tys,_) = getInstantiatedDataConSig con tycon_arg_tys
147 newSysLocalsDs arg_tys `thenDs` \ arg_ids ->
149 -- Now we are ready to construct the new alternative
151 new_alt = (con, arg_ids, MatchResult CanFail ty1 id NoMatchContext)
153 returnDs (MatchResult CanFail
155 (mk_case (new_alt:alts) (\ignore -> CoNoDefault))
158 other -> -- Many constructors missing, so use a default case
159 newSysLocalDs scrut_ty `thenDs` \ wild ->
160 returnDs (MatchResult CanFail
162 (mk_case alts (\fail_expr -> CoBindDefault wild fail_expr))
165 scrut_ty = getIdUniType var
166 (tycon, tycon_arg_tys, data_cons) = getUniDataTyCon scrut_ty
168 un_mentioned_constructors
169 = uniqSetToList (mkUniqSet data_cons `minusUniqSet` mkUniqSet [ con | (con, _, _) <- alts] )
171 match_results = [match_result | (_,_,match_result) <- alts]
172 (MatchResult _ ty1 _ cxt1 : _) = match_results
173 can_any_alt_fail = foldr1 orFail [can_it_fail | MatchResult can_it_fail _ _ _ <- match_results]
175 mk_case alts deflt_fn fail_expr
176 = CoCase (CoVar var) (CoAlgAlts final_alts (deflt_fn fail_expr))
178 final_alts = [ (con, args, body_fn fail_expr)
179 | (con, args, MatchResult _ _ body_fn _) <- alts
183 combineMatchResults :: MatchResult -> MatchResult -> DsM MatchResult
184 combineMatchResults (MatchResult CanFail ty1 body_fn1 cxt1)
185 (MatchResult can_it_fail2 ty2 body_fn2 cxt2)
186 = mkFailurePair ty1 `thenDs` \ (bind_fn, duplicatable_expr) ->
188 new_body_fn1 = \body1 -> CoLet (bind_fn body1) (body_fn1 duplicatable_expr)
189 new_body_fn2 = \body2 -> new_body_fn1 (body_fn2 body2)
191 returnDs (MatchResult can_it_fail2 ty1 new_body_fn2 cxt1)
193 combineMatchResults match_result1@(MatchResult CantFail ty body_fn1 cxt1)
195 = returnDs match_result1
198 -- The difference in combineGRHSMatchResults is that there is no
199 -- need to let-bind to avoid code duplication
200 combineGRHSMatchResults :: MatchResult -> MatchResult -> DsM MatchResult
201 combineGRHSMatchResults (MatchResult CanFail ty1 body_fn1 cxt1)
202 (MatchResult can_it_fail ty2 body_fn2 cxt2)
203 = returnDs (MatchResult can_it_fail ty1 (\ body -> body_fn1 (body_fn2 body)) cxt1)
205 combineGRHSMatchResults match_result1 match_result2
206 = -- Delegate to avoid duplication of code
207 combineMatchResults match_result1 match_result2
210 %************************************************************************
212 \subsection[dsExprToAtom]{Take an expression and produce an atom}
214 %************************************************************************
217 dsExprToAtom :: PlainCoreExpr -- The argument expression
218 -> (PlainCoreAtom -> DsM PlainCoreExpr) -- Something taking the argument *atom*,
219 -- and delivering an expression E
220 -> DsM PlainCoreExpr -- Either E or let x=arg-expr in E
222 dsExprToAtom (CoVar v) continue_with = continue_with (CoVarAtom v)
223 dsExprToAtom (CoLit v) continue_with = continue_with (CoLitAtom v)
225 dsExprToAtom arg_expr continue_with
226 = newSysLocalDs ty `thenDs` \ arg_id ->
227 continue_with (CoVarAtom arg_id) `thenDs` \ body ->
228 if isUnboxedDataType ty
229 then returnDs (CoCase arg_expr (CoPrimAlts [] (CoBindDefault arg_id body)))
230 else returnDs (CoLet (CoNonRec arg_id arg_expr) body)
232 ty = typeOfCoreExpr arg_expr
234 dsExprsToAtoms :: [PlainCoreExpr]
235 -> ([PlainCoreAtom] -> DsM PlainCoreExpr)
238 dsExprsToAtoms [] continue_with
241 dsExprsToAtoms (arg:args) continue_with
242 = dsExprToAtom arg (\ arg_atom ->
243 dsExprsToAtoms args (\ arg_atoms ->
244 continue_with (arg_atom:arg_atoms)
248 %************************************************************************
250 \subsection[mkCoAppDs]{Desugarer's versions of some Core functions}
252 %************************************************************************
254 Plumb the desugarer's @UniqueSupply@ in/out of the @UniqueSupplyMonad@
257 mkCoAppDs :: PlainCoreExpr -> PlainCoreExpr -> DsM PlainCoreExpr
258 mkCoConDs :: Id -> [UniType] -> [PlainCoreExpr] -> DsM PlainCoreExpr
259 mkCoPrimDs :: PrimOp -> [UniType] -> [PlainCoreExpr] -> DsM PlainCoreExpr
261 mkCoAppDs fun arg_expr
262 = dsExprToAtom arg_expr (\ arg_atom -> returnDs (CoApp fun arg_atom))
264 mkCoConDs con tys arg_exprs
265 = dsExprsToAtoms arg_exprs (\ arg_atoms -> returnDs (CoCon con tys arg_atoms))
267 mkCoPrimDs op tys arg_exprs
268 = dsExprsToAtoms arg_exprs (\ arg_atoms -> returnDs (CoPrim op tys arg_atoms))
271 %************************************************************************
273 \subsection[mkSelectorBind]{Make a selector bind}
275 %************************************************************************
277 This is used in various places to do with lazy patterns.
278 For each binder $b$ in the pattern, we create a binding:
280 b = case v of pat' -> b'
282 where pat' is pat with each binder b cloned into b'.
284 ToDo: making these bindings should really depend on whether there's
285 much work to be done per binding. If the pattern is complex, it
286 should be de-mangled once, into a tuple (and then selected from).
287 Otherwise the demangling can be in-line in the bindings (as here).
289 Boring! Boring! One error message per binder. The above ToDo is
290 even more helpful. Something very similar happens for pattern-bound
294 mkSelectorBinds :: [TyVar] -- Variables wrt which the pattern is polymorphic
295 -> TypecheckedPat -- The pattern
296 -> [(Id,Id)] -- Monomorphic and polymorphic binders for
298 -> PlainCoreExpr -- Expression to which the pattern is bound
299 -> DsM [(Id,PlainCoreExpr)]
301 mkSelectorBinds tyvars pat locals_and_globals val_expr
302 = getSrcLocDs `thenDs` \ (src_file, src_line) ->
304 if is_simple_tuple_pat pat then
305 mkTupleBind tyvars [] locals_and_globals val_expr
307 newSysLocalDs stringTy `thenDs` \ str_var -> -- to hold the string
309 src_loc_str = escErrorMsg ('"' : src_file) ++ "%l" ++ src_line
310 error_string = src_loc_str ++ "%~" --> ": pattern-match failed on an irrefutable pattern"
311 error_msg = mkErrorCoApp res_ty str_var error_string
313 matchSimply val_expr pat res_ty local_tuple error_msg `thenDs` \ tuple_expr ->
314 mkTupleBind tyvars [] locals_and_globals tuple_expr
316 locals = [local | (local, _) <- locals_and_globals]
317 local_tuple = mkTupleExpr locals
318 res_ty = typeOfCoreExpr local_tuple
320 is_simple_tuple_pat (TuplePat ps) = all is_var_pat ps
321 is_simple_tuple_pat other = False
323 is_var_pat (VarPat v) = True
324 is_var_pat other = False -- Even wild-card patterns aren't acceptable
327 We're about to match against some patterns. We want to make some
328 @Ids@ to use as match variables. If a pattern has an @Id@ readily at
329 hand, which should indeed be bound to the pattern as a whole, then use it;
330 otherwise, make one up.
332 selectMatchVars :: [TypecheckedPat] -> DsM [Id]
334 = mapDs var_from_pat_maybe pats
336 var_from_pat_maybe (VarPat var) = returnDs var
337 var_from_pat_maybe (AsPat var pat) = returnDs var
338 var_from_pat_maybe (LazyPat pat) = var_from_pat_maybe pat
340 -- var_from_pat_maybe (NPlusKPat n _ _ _ _ _) = returnDs n
341 -- WRONG! We don't want to bind n to the pattern as a whole!
343 var_from_pat_maybe other_pat
344 = newSysLocalDs (typeOfPat other_pat) -- OK, better make up one...
348 mkTupleBind :: [TyVar] -- Abstract wrt these...
349 -> [DictVar] -- ... and these
351 -> [(Id, Id)] -- Local, global pairs, equal in number
352 -- to the size of the tuple. The types
353 -- of the globals is the generalisation of
354 -- the corresp local, wrt the tyvars and dicts
356 -> PlainCoreExpr -- Expr whose value is a tuple; the expression
357 -- may mention the tyvars and dicts
359 -> DsM [(Id, PlainCoreExpr)] -- Bindings for the globals
364 mkTupleBind tyvars dicts [(l1,g1), ..., (ln,gn)] tup_expr
366 If $n=1$, the result is:
368 g1 = /\ tyvars -> \ dicts -> rhs
370 Otherwise, the result is:
372 tup = /\ tyvars -> \ dicts -> tup_expr
373 g1 = /\ tyvars -> \ dicts -> case (tup tyvars dicts) of
379 mkTupleBind tyvars dicts [(local,global)] tuple_expr
380 = returnDs [(global, mkCoTyLam tyvars (mkCoLam dicts tuple_expr))]
386 mkTupleBind tyvars dicts local_global_prs tuple_expr
387 = newSysLocalDs tuple_var_ty `thenDs` \ tuple_var ->
389 zipWithDs (mk_selector (CoVar tuple_var))
391 [(0::Int) .. (length local_global_prs - 1)]
392 `thenDs` \ tup_selectors ->
394 (tuple_var, mkCoTyLam tyvars (mkCoLam dicts tuple_expr)) :
398 locals, globals :: [Id]
399 locals = [local | (local,global) <- local_global_prs]
400 globals = [global | (local,global) <- local_global_prs]
402 no_of_binders = length local_global_prs
403 tyvar_tys = map mkTyVarTy tyvars
405 tuple_var_ty :: UniType
407 = case (quantifyTy tyvars (mkRhoTy theta
408 (applyTyCon (mkTupleTyCon no_of_binders)
409 (map getIdUniType locals)))) of
410 (_{-tossed templates-}, ty) -> ty
412 theta = map (splitDictType . getIdUniType) dicts
414 mk_selector :: PlainCoreExpr -> (Id, Id) -> Int -> DsM (Id, PlainCoreExpr)
416 mk_selector tuple_var_expr (local, global) which_local
417 = mapDs duplicateLocalDs locals{-the whole bunch-} `thenDs` \ binders ->
419 selected = binders !! which_local
422 (global, mkCoTyLam tyvars (
424 mkTupleSelector (mkCoApp_XX (mkCoTyApps tuple_var_expr tyvar_tys) dicts)
428 mkCoApp_XX :: PlainCoreExpr -> [Id] -> PlainCoreExpr
429 mkCoApp_XX expr [] = expr
430 mkCoApp_XX expr (id:ids) = mkCoApp_XX (CoApp expr (CoVarAtom id)) ids
435 @mkTupleExpr@ builds a tuple; the inverse to mkTupleSelector.
436 If it has only one element, it is
437 the identity function.
440 mkTupleExpr :: [Id] -> PlainCoreExpr
442 mkTupleExpr [] = CoCon (mkTupleCon 0) [] []
443 mkTupleExpr [id] = CoVar id
444 mkTupleExpr ids = CoCon (mkTupleCon (length ids))
445 (map getIdUniType ids)
446 [ CoVarAtom i | i <- ids ]
450 @mkTupleSelector@ builds a selector which scrutises the given
451 expression and extracts the one name from the list given.
452 If you want the no-shadowing rule to apply, the caller
453 is responsible for making sure that none of these names
456 If there is just one id in the ``tuple'', then the selector is
460 mkTupleSelector :: PlainCoreExpr -- Scrutinee
461 -> [Id] -- The tuple args
462 -> Id -- The selected one
465 mkTupleSelector expr [] the_var = panic "mkTupleSelector"
467 mkTupleSelector expr [var] should_be_the_same_var
468 = ASSERT(var == should_be_the_same_var)
471 mkTupleSelector expr vars the_var
472 = CoCase expr (CoAlgAlts [(mkTupleCon arity, vars, CoVar the_var)]
479 %************************************************************************
481 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
483 %************************************************************************
485 Generally, we handle pattern matching failure like this: let-bind a
486 fail-variable, and use that variable if the thing fails:
488 let fail.33 = error "Help"
499 If the case can't fail, then there'll be no mention of fail.33, and the
500 simplifier will later discard it.
503 If it can fail in only one way, then the simplifier will inline it.
506 Only if it is used more than once will the let-binding remain.
509 There's a problem when the result of the case expression is of
510 unboxed type. Then the type of fail.33 is unboxed too, and
511 there is every chance that someone will change the let into a case:
517 which is of course utterly wrong. Rather than drop the condition that
518 only boxed types can be let-bound, we just turn the fail into a function
519 for the primitive case:
521 let fail.33 :: () -> Int#
522 fail.33 = \_ -> error "Help"
531 Now fail.33 is a function, so it can be let-bound.
534 mkFailurePair :: UniType -- Result type of the whole case expression
535 -> DsM (PlainCoreExpr -> PlainCoreBinding,
536 -- Binds the newly-created fail variable
537 -- to either the expression or \_ -> expression
538 PlainCoreExpr) -- Either the fail variable, or fail variable
539 -- applied to unit tuple
541 | isUnboxedDataType ty
542 = newFailLocalDs (mkFunTy unit_ty ty) `thenDs` \ fail_fun_var ->
543 newSysLocalDs unit_ty `thenDs` \ fail_fun_arg ->
544 returnDs (\ body -> CoNonRec fail_fun_var (CoLam [fail_fun_arg] body),
545 CoApp (CoVar fail_fun_var) (CoVarAtom unit_id))
548 = newFailLocalDs ty `thenDs` \ fail_var ->
549 returnDs (\ body -> CoNonRec fail_var body, CoVar fail_var)
551 unit_id :: Id -- out here to avoid CAF (sigh)
552 unit_id = mkTupleCon 0
555 unit_ty = getIdUniType unit_id