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.
9 #include "HsVersions.h"
12 CanItFail(..), EquationInfo(..), MatchResult(..),
14 combineGRHSMatchResults,
16 dsExprToAtom, SYN_IE(DsCoreArg),
17 mkCoAlgCaseMatchResult,
18 mkAppDs, mkConDs, mkPrimDs, mkErrorAppDs,
20 mkCoPrimCaseMatchResult,
31 IMPORT_DELOOPER(DsLoop) ( match, matchSimply )
33 import HsSyn ( HsExpr(..), OutPat(..), HsLit(..), Fixity,
34 Match, HsBinds, Stmt, DoOrListComp, HsType, ArithSeqInfo )
35 import TcHsSyn ( SYN_IE(TypecheckedPat) )
36 import DsHsSyn ( outPatType )
41 import CoreUtils ( coreExprType, mkCoreIfThenElse )
42 import PprStyle ( PprStyle(..) )
43 import PrelVals ( iRREFUT_PAT_ERROR_ID, voidId )
44 import Pretty ( ppShow, ppBesides, ppStr )
45 import Id ( idType, dataConArgTys,
47 SYN_IE(DataCon), SYN_IE(DictVar), SYN_IE(Id), GenId )
48 import Literal ( Literal(..) )
49 import PprType ( GenType, GenTyVar )
50 import TyCon ( isNewTyCon, tyConDataCons )
51 import Type ( mkTyVarTys, mkRhoTy, mkForAllTys, mkFunTy,
52 mkTheta, isUnboxedType, applyTyCon, getAppTyCon,
53 GenType {- instances -}
55 import TyVar ( GenTyVar {- instances -} )
56 import TysPrim ( voidTy )
57 import TysWiredIn ( tupleTyCon, unitDataCon, tupleCon )
58 import UniqSet ( mkUniqSet, minusUniqSet, uniqSetToList, SYN_IE(UniqSet) )
59 import Util ( panic, assertPanic{-, pprTrace ToDo:rm-} )
60 import Unique ( Unique )
61 import Usage ( SYN_IE(UVar) )
62 import SrcLoc ( SrcLoc {- instance Outputable -} )
65 %************************************************************************
67 %* type synonym EquationInfo and access functions for its pieces *
69 %************************************************************************
70 \subsection[EquationInfo-synonym]{@EquationInfo@: a useful synonym}
72 The ``equation info'' used by @match@ is relatively complicated and
73 worthy of a type synonym and a few handy functions.
78 [TypecheckedPat] -- the patterns for an eqn
79 MatchResult -- Encapsulates the guards and bindings
86 Type -- Type of argument expression
88 (CoreExpr -> CoreExpr)
89 -- Takes a expression to plug in at the
90 -- failure point(s). The expression should
93 DsMatchContext -- The context info is used when producing warnings
94 -- about shadowed patterns. It's the context
95 -- of the *first* thing matched in this group.
96 -- Should perhaps be a list of them all!
98 data CanItFail = CanFail | CantFail
100 orFail CantFail CantFail = CantFail
104 mkCoLetsMatchResult :: [CoreBinding] -> MatchResult -> MatchResult
105 mkCoLetsMatchResult binds (MatchResult can_it_fail ty body_fn cxt)
106 = MatchResult can_it_fail ty (\body -> mkCoLetsAny binds (body_fn body)) cxt
108 mkGuardedMatchResult :: CoreExpr -> MatchResult -> DsM MatchResult
109 mkGuardedMatchResult pred_expr (MatchResult can_it_fail ty body_fn cxt)
110 = returnDs (MatchResult CanFail
112 (\fail -> mkCoreIfThenElse pred_expr (body_fn fail) fail)
116 mkCoPrimCaseMatchResult :: Id -- Scrutinee
117 -> [(Literal, MatchResult)] -- Alternatives
119 mkCoPrimCaseMatchResult var alts
120 = newSysLocalDs (idType var) `thenDs` \ wild ->
121 returnDs (MatchResult CanFail
126 ((_,MatchResult _ ty1 _ cxt1) : _) = alts
128 mk_case alts wild fail_expr
129 = Case (Var var) (PrimAlts final_alts (BindDefault wild fail_expr))
131 final_alts = [ (lit, body_fn fail_expr)
132 | (lit, MatchResult _ _ body_fn _) <- alts
136 mkCoAlgCaseMatchResult :: Id -- Scrutinee
137 -> [(DataCon, [Id], MatchResult)] -- Alternatives
140 mkCoAlgCaseMatchResult var alts
141 | isNewTyCon tycon -- newtype case; use a let
142 = ASSERT( newtype_sanity )
143 returnDs (mkCoLetsMatchResult [coercion_bind] match_result)
145 | otherwise -- datatype case
146 = -- Find all the constructors in the type which aren't
147 -- explicitly mentioned in the alternatives:
148 case un_mentioned_constructors of
149 [] -> -- All constructors mentioned, so no default needed
150 returnDs (MatchResult can_any_alt_fail
152 (mk_case alts (\ignore -> NoDefault))
155 [con] -> -- Just one constructor missing, so add a case for it
156 -- We need to build new locals for the args of the constructor,
157 -- and figuring out their types is somewhat tiresome.
159 arg_tys = dataConArgTys con tycon_arg_tys
161 newSysLocalsDs arg_tys `thenDs` \ arg_ids ->
163 -- Now we are ready to construct the new alternative
165 new_alt = (con, arg_ids, MatchResult CanFail ty1 id NoMatchContext)
167 returnDs (MatchResult CanFail
169 (mk_case (new_alt:alts) (\ignore -> NoDefault))
172 other -> -- Many constructors missing, so use a default case
173 newSysLocalDs scrut_ty `thenDs` \ wild ->
174 returnDs (MatchResult CanFail
176 (mk_case alts (\fail_expr -> BindDefault wild fail_expr))
180 scrut_ty = idType var
181 (tycon, tycon_arg_tys) = --pprTrace "CoAlgCase:" (pprType PprDebug scrut_ty) $
185 (con_id, arg_ids, match_result) = head alts
186 arg_id = head arg_ids
187 coercion_bind = NonRec arg_id (Coerce (CoerceOut con_id)
190 newtype_sanity = null (tail alts) && null (tail arg_ids)
192 -- Stuff for data types
193 data_cons = tyConDataCons tycon
195 un_mentioned_constructors
196 = uniqSetToList (mkUniqSet data_cons `minusUniqSet` mkUniqSet [ con | (con, _, _) <- alts] )
198 match_results = [match_result | (_,_,match_result) <- alts]
199 (MatchResult _ ty1 _ cxt1 : _) = match_results
200 can_any_alt_fail = foldr1 orFail [can_it_fail | MatchResult can_it_fail _ _ _ <- match_results]
202 mk_case alts deflt_fn fail_expr
203 = Case (Var var) (AlgAlts final_alts (deflt_fn fail_expr))
205 final_alts = [ (con, args, body_fn fail_expr)
206 | (con, args, MatchResult _ _ body_fn _) <- alts
210 combineMatchResults :: MatchResult -> MatchResult -> DsM MatchResult
211 combineMatchResults (MatchResult CanFail ty1 body_fn1 cxt1)
212 (MatchResult can_it_fail2 ty2 body_fn2 cxt2)
213 = mkFailurePair ty1 `thenDs` \ (bind_fn, duplicatable_expr) ->
215 new_body_fn1 = \body1 -> Let (bind_fn body1) (body_fn1 duplicatable_expr)
216 new_body_fn2 = \body2 -> new_body_fn1 (body_fn2 body2)
218 returnDs (MatchResult can_it_fail2 ty1 new_body_fn2 cxt1)
220 combineMatchResults match_result1@(MatchResult CantFail ty body_fn1 cxt1)
222 = returnDs match_result1
225 -- The difference in combineGRHSMatchResults is that there is no
226 -- need to let-bind to avoid code duplication
227 combineGRHSMatchResults :: MatchResult -> MatchResult -> DsM MatchResult
228 combineGRHSMatchResults (MatchResult CanFail ty1 body_fn1 cxt1)
229 (MatchResult can_it_fail ty2 body_fn2 cxt2)
230 = returnDs (MatchResult can_it_fail ty1 (\ body -> body_fn1 (body_fn2 body)) cxt1)
232 combineGRHSMatchResults match_result1 match_result2
233 = -- Delegate to avoid duplication of code
234 combineMatchResults match_result1 match_result2
237 %************************************************************************
239 \subsection[dsExprToAtom]{Take an expression and produce an atom}
241 %************************************************************************
244 dsExprToAtom :: DsCoreArg -- The argument expression
245 -> (CoreArg -> DsM CoreExpr) -- Something taking the argument *atom*,
246 -- and delivering an expression E
247 -> DsM CoreExpr -- Either E or let x=arg-expr in E
249 dsExprToAtom (UsageArg u) continue_with = continue_with (UsageArg u)
250 dsExprToAtom (TyArg t) continue_with = continue_with (TyArg t)
251 dsExprToAtom (LitArg l) continue_with = continue_with (LitArg l)
253 dsExprToAtom (VarArg (Var v)) continue_with = continue_with (VarArg v)
254 dsExprToAtom (VarArg (Lit v)) continue_with = continue_with (LitArg v)
256 dsExprToAtom (VarArg arg_expr) continue_with
258 ty = coreExprType arg_expr
260 newSysLocalDs ty `thenDs` \ arg_id ->
261 continue_with (VarArg arg_id) `thenDs` \ body ->
264 then Case arg_expr (PrimAlts [] (BindDefault arg_id body))
265 else Let (NonRec arg_id arg_expr) body
268 dsExprsToAtoms :: [DsCoreArg]
269 -> ([CoreArg] -> DsM CoreExpr)
272 dsExprsToAtoms [] continue_with = continue_with []
274 dsExprsToAtoms (arg:args) continue_with
275 = dsExprToAtom arg $ \ arg_atom ->
276 dsExprsToAtoms args $ \ arg_atoms ->
277 continue_with (arg_atom:arg_atoms)
280 %************************************************************************
282 \subsection{Desugarer's versions of some Core functions}
284 %************************************************************************
287 type DsCoreArg = GenCoreArg CoreExpr{-NB!-} TyVar UVar
289 mkAppDs :: CoreExpr -> [DsCoreArg] -> DsM CoreExpr
290 mkConDs :: Id -> [DsCoreArg] -> DsM CoreExpr
291 mkPrimDs :: PrimOp -> [DsCoreArg] -> DsM CoreExpr
294 = dsExprsToAtoms args $ \ atoms ->
295 returnDs (mkGenApp fun atoms)
298 = dsExprsToAtoms args $ \ atoms ->
299 returnDs (Con con atoms)
302 = dsExprsToAtoms args $ \ atoms ->
303 returnDs (Prim op atoms)
307 showForErr :: Outputable a => a -> String -- Boring but useful
308 showForErr thing = ppShow 80 (ppr PprForUser thing)
310 mkErrorAppDs :: Id -- The error function
311 -> Type -- Type to which it should be applied
312 -> String -- The error message string to pass
315 mkErrorAppDs err_id ty msg
316 = getSrcLocDs `thenDs` \ src_loc ->
318 full_msg = ppShow 80 (ppBesides [ppr PprForUser src_loc, ppStr "|", ppStr msg])
319 msg_lit = NoRepStr (_PK_ full_msg)
321 returnDs (mkApp (Var err_id) [] [ty] [LitArg msg_lit])
324 %************************************************************************
326 \subsection[mkSelectorBind]{Make a selector bind}
328 %************************************************************************
330 This is used in various places to do with lazy patterns.
331 For each binder $b$ in the pattern, we create a binding:
333 b = case v of pat' -> b'
335 where pat' is pat with each binder b cloned into b'.
337 ToDo: making these bindings should really depend on whether there's
338 much work to be done per binding. If the pattern is complex, it
339 should be de-mangled once, into a tuple (and then selected from).
340 Otherwise the demangling can be in-line in the bindings (as here).
342 Boring! Boring! One error message per binder. The above ToDo is
343 even more helpful. Something very similar happens for pattern-bound
347 mkSelectorBinds :: [TyVar] -- Variables wrt which the pattern is polymorphic
348 -> TypecheckedPat -- The pattern
349 -> [(Id,Id)] -- Monomorphic and polymorphic binders for
351 -> CoreExpr -- Expression to which the pattern is bound
352 -> DsM [(Id,CoreExpr)]
354 mkSelectorBinds tyvars pat locals_and_globals val_expr
355 = if is_simple_tuple_pat pat then
356 mkTupleBind tyvars [] locals_and_globals val_expr
358 mkErrorAppDs iRREFUT_PAT_ERROR_ID res_ty pat_string `thenDs` \ error_msg ->
359 matchSimply val_expr pat res_ty local_tuple error_msg `thenDs` \ tuple_expr ->
360 mkTupleBind tyvars [] locals_and_globals tuple_expr
362 locals = [local | (local, _) <- locals_and_globals]
363 local_tuple = mkTupleExpr locals
364 res_ty = coreExprType local_tuple
366 is_simple_tuple_pat (TuplePat ps) = all is_var_pat ps
367 is_simple_tuple_pat other = False
369 is_var_pat (VarPat v) = True
370 is_var_pat other = False -- Even wild-card patterns aren't acceptable
372 pat_string = ppShow 80 (ppr PprForUser pat)
375 We're about to match against some patterns. We want to make some
376 @Ids@ to use as match variables. If a pattern has an @Id@ readily at
377 hand, which should indeed be bound to the pattern as a whole, then use it;
378 otherwise, make one up.
380 selectMatchVars :: [TypecheckedPat] -> DsM [Id]
382 = mapDs var_from_pat_maybe pats
384 var_from_pat_maybe (VarPat var) = returnDs var
385 var_from_pat_maybe (AsPat var pat) = returnDs var
386 var_from_pat_maybe (LazyPat pat) = var_from_pat_maybe pat
387 var_from_pat_maybe other_pat
388 = newSysLocalDs (outPatType other_pat) -- OK, better make up one...
392 mkTupleBind :: [TyVar] -- Abstract wrt these...
393 -> [DictVar] -- ... and these
395 -> [(Id, Id)] -- Local, global pairs, equal in number
396 -- to the size of the tuple. The types
397 -- of the globals is the generalisation of
398 -- the corresp local, wrt the tyvars and dicts
400 -> CoreExpr -- Expr whose value is a tuple; the expression
401 -- may mention the tyvars and dicts
403 -> DsM [(Id, CoreExpr)] -- Bindings for the globals
408 mkTupleBind tyvars dicts [(l1,g1), ..., (ln,gn)] tup_expr
410 If $n=1$, the result is:
412 g1 = /\ tyvars -> \ dicts -> rhs
414 Otherwise, the result is:
416 tup = /\ tyvars -> \ dicts -> tup_expr
417 g1 = /\ tyvars -> \ dicts -> case (tup tyvars dicts) of
423 mkTupleBind tyvars dicts [(local,global)] tuple_expr
424 = returnDs [(global, mkLam tyvars dicts tuple_expr)]
430 mkTupleBind tyvars dicts local_global_prs tuple_expr
431 = --pprTrace "mkTupleBind:\n" (ppAboves [ppCat (map (pprId PprShowAll) locals), ppCat (map (pprId PprShowAll) globals), {-ppr PprDebug local_tuple, pprType PprDebug res_ty,-} ppr PprDebug tuple_expr]) $
433 newSysLocalDs tuple_var_ty `thenDs` \ tuple_var ->
435 zipWithDs (mk_selector (Var tuple_var))
437 [(0::Int) .. (length local_global_prs - 1)]
438 `thenDs` \ tup_selectors ->
440 (tuple_var, mkLam tyvars dicts tuple_expr)
444 locals, globals :: [Id]
445 locals = [local | (local,global) <- local_global_prs]
446 globals = [global | (local,global) <- local_global_prs]
448 no_of_binders = length local_global_prs
449 tyvar_tys = mkTyVarTys tyvars
453 = mkForAllTys tyvars $
455 applyTyCon (tupleTyCon no_of_binders)
458 theta = mkTheta (map idType dicts)
460 mk_selector :: CoreExpr -> (Id, Id) -> Int -> DsM (Id, CoreExpr)
462 mk_selector tuple_var_expr (local, global) which_local
463 = mapDs duplicateLocalDs locals{-the whole bunch-} `thenDs` \ binders ->
465 selected = binders !! which_local
471 (mkValApp (mkTyApp tuple_var_expr tyvar_tys)
478 @mkTupleExpr@ builds a tuple; the inverse to @mkTupleSelector@. If it
479 has only one element, it is the identity function.
481 mkTupleExpr :: [Id] -> CoreExpr
483 mkTupleExpr [] = Con unitDataCon []
484 mkTupleExpr [id] = Var id
485 mkTupleExpr ids = mkCon (tupleCon (length ids))
488 [ VarArg i | i <- ids ]
492 @mkTupleSelector@ builds a selector which scrutises the given
493 expression and extracts the one name from the list given.
494 If you want the no-shadowing rule to apply, the caller
495 is responsible for making sure that none of these names
498 If there is just one id in the ``tuple'', then the selector is
502 mkTupleSelector :: CoreExpr -- Scrutinee
503 -> [Id] -- The tuple args
504 -> Id -- The selected one
507 mkTupleSelector expr [] the_var = panic "mkTupleSelector"
509 mkTupleSelector expr [var] should_be_the_same_var
510 = ASSERT(var == should_be_the_same_var)
513 mkTupleSelector expr vars the_var
514 = Case expr (AlgAlts [(tupleCon arity, vars, Var the_var)]
521 %************************************************************************
523 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
525 %************************************************************************
527 Generally, we handle pattern matching failure like this: let-bind a
528 fail-variable, and use that variable if the thing fails:
530 let fail.33 = error "Help"
541 If the case can't fail, then there'll be no mention of fail.33, and the
542 simplifier will later discard it.
545 If it can fail in only one way, then the simplifier will inline it.
548 Only if it is used more than once will the let-binding remain.
551 There's a problem when the result of the case expression is of
552 unboxed type. Then the type of fail.33 is unboxed too, and
553 there is every chance that someone will change the let into a case:
559 which is of course utterly wrong. Rather than drop the condition that
560 only boxed types can be let-bound, we just turn the fail into a function
561 for the primitive case:
563 let fail.33 :: Void -> Int#
564 fail.33 = \_ -> error "Help"
573 Now fail.33 is a function, so it can be let-bound.
576 mkFailurePair :: Type -- Result type of the whole case expression
577 -> DsM (CoreExpr -> CoreBinding,
578 -- Binds the newly-created fail variable
579 -- to either the expression or \ _ -> expression
580 CoreExpr) -- Either the fail variable, or fail variable
581 -- applied to unit tuple
584 = newFailLocalDs (voidTy `mkFunTy` ty) `thenDs` \ fail_fun_var ->
585 newSysLocalDs voidTy `thenDs` \ fail_fun_arg ->
587 NonRec fail_fun_var (Lam (ValBinder fail_fun_arg) body),
588 App (Var fail_fun_var) (VarArg voidId))
591 = newFailLocalDs ty `thenDs` \ fail_var ->
592 returnDs (\ body -> NonRec fail_var body, Var fail_var)