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,
17 mkCoAlgCaseMatchResult,
18 mkAppDs, mkConDs, mkPrimDs, mkErrorAppDs,
20 mkCoPrimCaseMatchResult,
31 import DsLoop ( match, matchSimply )
33 import HsSyn ( HsExpr(..), OutPat(..), HsLit(..),
34 Match, HsBinds, Stmt, Qual, PolyType, ArithSeqInfo )
35 import TcHsSyn ( TypecheckedPat(..) )
36 import DsHsSyn ( outPatType )
41 import CoreUtils ( coreExprType, mkCoreIfThenElse )
42 import PprStyle ( PprStyle(..) )
43 import PrelInfo ( stringTy, iRREFUT_PAT_ERROR_ID )
44 import Pretty ( ppShow )
45 import Id ( idType, dataConArgTys, mkTupleCon,
47 DataCon(..), DictVar(..), Id(..), GenId )
48 import Literal ( Literal(..) )
49 import TyCon ( mkTupleTyCon, isNewTyCon, tyConDataCons )
50 import Type ( mkTyVarTys, mkRhoTy, mkForAllTys, mkFunTys,
51 isUnboxedType, applyTyCon,
52 getAppDataTyCon, getAppTyCon
54 import UniqSet ( mkUniqSet, minusUniqSet, uniqSetToList, UniqSet(..) )
55 import Util ( panic, assertPanic, pprTrace{-ToDo:rm-} )
56 import PprCore{-ToDo:rm-}
57 import PprType--ToDo:rm
58 import Pretty--ToDo:rm
60 import Unique--ToDo:rm
63 splitDictType = panic "DsUtils.splitDictType"
66 %************************************************************************
68 %* type synonym EquationInfo and access functions for its pieces *
70 %************************************************************************
71 \subsection[EquationInfo-synonym]{@EquationInfo@: a useful synonym}
73 The ``equation info'' used by @match@ is relatively complicated and
74 worthy of a type synonym and a few handy functions.
79 [TypecheckedPat] -- the patterns for an eqn
80 MatchResult -- Encapsulates the guards and bindings
87 Type -- Type of argument expression
89 (CoreExpr -> CoreExpr)
90 -- Takes a expression to plug in at the
91 -- failure point(s). The expression should
94 DsMatchContext -- The context info is used when producing warnings
95 -- about shadowed patterns. It's the context
96 -- of the *first* thing matched in this group.
97 -- Should perhaps be a list of them all!
99 data CanItFail = CanFail | CantFail
101 orFail CantFail CantFail = CantFail
105 mkCoLetsMatchResult :: [CoreBinding] -> MatchResult -> MatchResult
106 mkCoLetsMatchResult binds (MatchResult can_it_fail ty body_fn cxt)
107 = MatchResult can_it_fail ty (\body -> mkCoLetsAny binds (body_fn body)) cxt
109 mkGuardedMatchResult :: CoreExpr -> MatchResult -> DsM MatchResult
110 mkGuardedMatchResult pred_expr (MatchResult can_it_fail ty body_fn cxt)
111 = returnDs (MatchResult CanFail
113 (\fail -> mkCoreIfThenElse pred_expr (body_fn fail) fail)
117 mkCoPrimCaseMatchResult :: Id -- Scrutinee
118 -> [(Literal, MatchResult)] -- Alternatives
120 mkCoPrimCaseMatchResult var alts
121 = newSysLocalDs (idType var) `thenDs` \ wild ->
122 returnDs (MatchResult CanFail
127 ((_,MatchResult _ ty1 _ cxt1) : _) = alts
129 mk_case alts wild fail_expr
130 = Case (Var var) (PrimAlts final_alts (BindDefault wild fail_expr))
132 final_alts = [ (lit, body_fn fail_expr)
133 | (lit, MatchResult _ _ body_fn _) <- alts
137 mkCoAlgCaseMatchResult :: Id -- Scrutinee
138 -> [(DataCon, [Id], MatchResult)] -- Alternatives
141 mkCoAlgCaseMatchResult var alts
142 | isNewTyCon tycon -- newtype case; use a let
143 = ASSERT( newtype_sanity )
144 returnDs (mkCoLetsMatchResult [coercion_bind] match_result)
146 | otherwise -- datatype case
147 = -- Find all the constructors in the type which aren't
148 -- explicitly mentioned in the alternatives:
149 case un_mentioned_constructors of
150 [] -> -- All constructors mentioned, so no default needed
151 returnDs (MatchResult can_any_alt_fail
153 (mk_case alts (\ignore -> NoDefault))
156 [con] -> -- Just one constructor missing, so add a case for it
157 -- We need to build new locals for the args of the constructor,
158 -- and figuring out their types is somewhat tiresome.
160 arg_tys = dataConArgTys con tycon_arg_tys
162 newSysLocalsDs arg_tys `thenDs` \ arg_ids ->
164 -- Now we are ready to construct the new alternative
166 new_alt = (con, arg_ids, MatchResult CanFail ty1 id NoMatchContext)
168 returnDs (MatchResult CanFail
170 (mk_case (new_alt:alts) (\ignore -> NoDefault))
173 other -> -- Many constructors missing, so use a default case
174 newSysLocalDs scrut_ty `thenDs` \ wild ->
175 returnDs (MatchResult CanFail
177 (mk_case alts (\fail_expr -> BindDefault wild fail_expr))
181 scrut_ty = idType var
182 (tycon, tycon_arg_tys) = --pprTrace "CoAlgCase:" (pprType PprDebug scrut_ty) $
186 (con_id, arg_ids, match_result) = head alts
187 arg_id = head arg_ids
188 coercion_bind = NonRec arg_id (Coerce (CoerceOut con_id)
191 newtype_sanity = null (tail alts) && null (tail arg_ids)
193 -- Stuff for data types
194 data_cons = tyConDataCons tycon
196 un_mentioned_constructors
197 = uniqSetToList (mkUniqSet data_cons `minusUniqSet` mkUniqSet [ con | (con, _, _) <- alts] )
199 match_results = [match_result | (_,_,match_result) <- alts]
200 (MatchResult _ ty1 _ cxt1 : _) = match_results
201 can_any_alt_fail = foldr1 orFail [can_it_fail | MatchResult can_it_fail _ _ _ <- match_results]
203 mk_case alts deflt_fn fail_expr
204 = Case (Var var) (AlgAlts final_alts (deflt_fn fail_expr))
206 final_alts = [ (con, args, body_fn fail_expr)
207 | (con, args, MatchResult _ _ body_fn _) <- alts
211 combineMatchResults :: MatchResult -> MatchResult -> DsM MatchResult
212 combineMatchResults (MatchResult CanFail ty1 body_fn1 cxt1)
213 (MatchResult can_it_fail2 ty2 body_fn2 cxt2)
214 = mkFailurePair ty1 `thenDs` \ (bind_fn, duplicatable_expr) ->
216 new_body_fn1 = \body1 -> Let (bind_fn body1) (body_fn1 duplicatable_expr)
217 new_body_fn2 = \body2 -> new_body_fn1 (body_fn2 body2)
219 returnDs (MatchResult can_it_fail2 ty1 new_body_fn2 cxt1)
221 combineMatchResults match_result1@(MatchResult CantFail ty body_fn1 cxt1)
223 = returnDs match_result1
226 -- The difference in combineGRHSMatchResults is that there is no
227 -- need to let-bind to avoid code duplication
228 combineGRHSMatchResults :: MatchResult -> MatchResult -> DsM MatchResult
229 combineGRHSMatchResults (MatchResult CanFail ty1 body_fn1 cxt1)
230 (MatchResult can_it_fail ty2 body_fn2 cxt2)
231 = returnDs (MatchResult can_it_fail ty1 (\ body -> body_fn1 (body_fn2 body)) cxt1)
233 combineGRHSMatchResults match_result1 match_result2
234 = -- Delegate to avoid duplication of code
235 combineMatchResults match_result1 match_result2
238 %************************************************************************
240 \subsection[dsExprToAtom]{Take an expression and produce an atom}
242 %************************************************************************
245 dsExprToAtom :: CoreExpr -- The argument expression
246 -> (CoreArg -> DsM CoreExpr) -- Something taking the argument *atom*,
247 -- and delivering an expression E
248 -> DsM CoreExpr -- Either E or let x=arg-expr in E
250 dsExprToAtom (Var v) continue_with = continue_with (VarArg v)
251 dsExprToAtom (Lit v) continue_with = continue_with (LitArg v)
253 dsExprToAtom arg_expr continue_with
255 ty = coreExprType arg_expr
257 newSysLocalDs ty `thenDs` \ arg_id ->
258 continue_with (VarArg arg_id) `thenDs` \ body ->
261 then Case arg_expr (PrimAlts [] (BindDefault arg_id body))
262 else Let (NonRec arg_id arg_expr) body
265 dsExprsToAtoms :: [CoreExpr]
266 -> ([CoreArg] -> DsM CoreExpr)
269 dsExprsToAtoms [] continue_with
272 dsExprsToAtoms (arg:args) continue_with
273 = dsExprToAtom arg $ \ arg_atom ->
274 dsExprsToAtoms args $ \ arg_atoms ->
275 continue_with (arg_atom:arg_atoms)
278 %************************************************************************
280 \subsection{Desugarer's versions of some Core functions}
282 %************************************************************************
285 mkAppDs :: CoreExpr -> [Type] -> [CoreExpr] -> DsM CoreExpr
286 mkConDs :: Id -> [Type] -> [CoreExpr] -> DsM CoreExpr
287 mkPrimDs :: PrimOp -> [Type] -> [CoreExpr] -> DsM CoreExpr
289 mkAppDs fun tys arg_exprs
290 = dsExprsToAtoms arg_exprs $ \ vals ->
291 returnDs (mkApp fun [] tys vals)
293 mkConDs con tys arg_exprs
294 = dsExprsToAtoms arg_exprs $ \ vals ->
295 returnDs (mkCon con [] tys vals)
297 mkPrimDs op tys arg_exprs
298 = dsExprsToAtoms arg_exprs $ \ vals ->
299 returnDs (mkPrim op [] tys vals)
303 showForErr :: Outputable a => a -> String -- Boring but useful
304 showForErr thing = ppShow 80 (ppr PprForUser thing)
306 mkErrorAppDs :: Id -- The error function
307 -> Type -- Type to which it should be applied
308 -> String -- The error message string to pass
311 mkErrorAppDs err_id ty msg
312 = getSrcLocDs `thenDs` \ (file, line) ->
314 full_msg = file ++ "|" ++ line ++ "|" ++msg
315 msg_lit = NoRepStr (_PK_ full_msg)
317 returnDs (mkApp (Var err_id) [] [ty] [LitArg msg_lit])
320 %************************************************************************
322 \subsection[mkSelectorBind]{Make a selector bind}
324 %************************************************************************
326 This is used in various places to do with lazy patterns.
327 For each binder $b$ in the pattern, we create a binding:
329 b = case v of pat' -> b'
331 where pat' is pat with each binder b cloned into b'.
333 ToDo: making these bindings should really depend on whether there's
334 much work to be done per binding. If the pattern is complex, it
335 should be de-mangled once, into a tuple (and then selected from).
336 Otherwise the demangling can be in-line in the bindings (as here).
338 Boring! Boring! One error message per binder. The above ToDo is
339 even more helpful. Something very similar happens for pattern-bound
343 mkSelectorBinds :: [TyVar] -- Variables wrt which the pattern is polymorphic
344 -> TypecheckedPat -- The pattern
345 -> [(Id,Id)] -- Monomorphic and polymorphic binders for
347 -> CoreExpr -- Expression to which the pattern is bound
348 -> DsM [(Id,CoreExpr)]
350 mkSelectorBinds tyvars pat locals_and_globals val_expr
351 = if is_simple_tuple_pat pat then
352 mkTupleBind tyvars [] locals_and_globals val_expr
354 mkErrorAppDs iRREFUT_PAT_ERROR_ID res_ty "" `thenDs` \ error_msg ->
355 matchSimply val_expr pat res_ty local_tuple error_msg `thenDs` \ tuple_expr ->
356 mkTupleBind tyvars [] locals_and_globals tuple_expr
358 locals = [local | (local, _) <- locals_and_globals]
359 local_tuple = mkTupleExpr locals
360 res_ty = coreExprType local_tuple
362 is_simple_tuple_pat (TuplePat ps) = all is_var_pat ps
363 is_simple_tuple_pat other = False
365 is_var_pat (VarPat v) = True
366 is_var_pat other = False -- Even wild-card patterns aren't acceptable
369 We're about to match against some patterns. We want to make some
370 @Ids@ to use as match variables. If a pattern has an @Id@ readily at
371 hand, which should indeed be bound to the pattern as a whole, then use it;
372 otherwise, make one up.
374 selectMatchVars :: [TypecheckedPat] -> DsM [Id]
376 = mapDs var_from_pat_maybe pats
378 var_from_pat_maybe (VarPat var) = returnDs var
379 var_from_pat_maybe (AsPat var pat) = returnDs var
380 var_from_pat_maybe (LazyPat pat) = var_from_pat_maybe pat
381 var_from_pat_maybe other_pat
382 = newSysLocalDs (outPatType other_pat) -- OK, better make up one...
386 mkTupleBind :: [TyVar] -- Abstract wrt these...
387 -> [DictVar] -- ... and these
389 -> [(Id, Id)] -- Local, global pairs, equal in number
390 -- to the size of the tuple. The types
391 -- of the globals is the generalisation of
392 -- the corresp local, wrt the tyvars and dicts
394 -> CoreExpr -- Expr whose value is a tuple; the expression
395 -- may mention the tyvars and dicts
397 -> DsM [(Id, CoreExpr)] -- Bindings for the globals
402 mkTupleBind tyvars dicts [(l1,g1), ..., (ln,gn)] tup_expr
404 If $n=1$, the result is:
406 g1 = /\ tyvars -> \ dicts -> rhs
408 Otherwise, the result is:
410 tup = /\ tyvars -> \ dicts -> tup_expr
411 g1 = /\ tyvars -> \ dicts -> case (tup tyvars dicts) of
417 mkTupleBind tyvars dicts [(local,global)] tuple_expr
418 = returnDs [(global, mkLam tyvars dicts tuple_expr)]
424 mkTupleBind tyvars dicts local_global_prs tuple_expr
425 = 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]) $
427 newSysLocalDs tuple_var_ty `thenDs` \ tuple_var ->
429 zipWithDs (mk_selector (Var tuple_var))
431 [(0::Int) .. (length local_global_prs - 1)]
432 `thenDs` \ tup_selectors ->
434 (tuple_var, mkLam tyvars dicts tuple_expr)
438 locals, globals :: [Id]
439 locals = [local | (local,global) <- local_global_prs]
440 globals = [global | (local,global) <- local_global_prs]
442 no_of_binders = length local_global_prs
443 tyvar_tys = mkTyVarTys tyvars
447 = mkForAllTys tyvars $
449 applyTyCon (mkTupleTyCon no_of_binders)
452 theta = map (splitDictType . idType) dicts
454 mk_selector :: CoreExpr -> (Id, Id) -> Int -> DsM (Id, CoreExpr)
456 mk_selector tuple_var_expr (local, global) which_local
457 = mapDs duplicateLocalDs locals{-the whole bunch-} `thenDs` \ binders ->
459 selected = binders !! which_local
465 (mkValApp (mkTyApp tuple_var_expr tyvar_tys)
472 @mkTupleExpr@ builds a tuple; the inverse to @mkTupleSelector@. If it
473 has only one element, it is the identity function.
475 mkTupleExpr :: [Id] -> CoreExpr
477 mkTupleExpr [] = Con (mkTupleCon 0) []
478 mkTupleExpr [id] = Var id
479 mkTupleExpr ids = mkCon (mkTupleCon (length ids))
482 [ VarArg i | i <- ids ]
486 @mkTupleSelector@ builds a selector which scrutises the given
487 expression and extracts the one name from the list given.
488 If you want the no-shadowing rule to apply, the caller
489 is responsible for making sure that none of these names
492 If there is just one id in the ``tuple'', then the selector is
496 mkTupleSelector :: CoreExpr -- Scrutinee
497 -> [Id] -- The tuple args
498 -> Id -- The selected one
501 mkTupleSelector expr [] the_var = panic "mkTupleSelector"
503 mkTupleSelector expr [var] should_be_the_same_var
504 = ASSERT(var == should_be_the_same_var)
507 mkTupleSelector expr vars the_var
508 = Case expr (AlgAlts [(mkTupleCon arity, vars, Var the_var)]
515 %************************************************************************
517 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
519 %************************************************************************
521 Generally, we handle pattern matching failure like this: let-bind a
522 fail-variable, and use that variable if the thing fails:
524 let fail.33 = error "Help"
535 If the case can't fail, then there'll be no mention of fail.33, and the
536 simplifier will later discard it.
539 If it can fail in only one way, then the simplifier will inline it.
542 Only if it is used more than once will the let-binding remain.
545 There's a problem when the result of the case expression is of
546 unboxed type. Then the type of fail.33 is unboxed too, and
547 there is every chance that someone will change the let into a case:
553 which is of course utterly wrong. Rather than drop the condition that
554 only boxed types can be let-bound, we just turn the fail into a function
555 for the primitive case:
557 let fail.33 :: () -> Int#
558 fail.33 = \_ -> error "Help"
567 Now fail.33 is a function, so it can be let-bound.
570 mkFailurePair :: Type -- Result type of the whole case expression
571 -> DsM (CoreExpr -> CoreBinding,
572 -- Binds the newly-created fail variable
573 -- to either the expression or \ _ -> expression
574 CoreExpr) -- Either the fail variable, or fail variable
575 -- applied to unit tuple
578 = newFailLocalDs (mkFunTys [unit_ty] ty) `thenDs` \ fail_fun_var ->
579 newSysLocalDs unit_ty `thenDs` \ fail_fun_arg ->
581 NonRec fail_fun_var (Lam (ValBinder fail_fun_arg) body),
582 App (Var fail_fun_var) (VarArg unit_id))
585 = newFailLocalDs ty `thenDs` \ fail_var ->
586 returnDs (\ body -> NonRec fail_var body, Var fail_var)
588 unit_id :: Id -- out here to avoid CAF (sigh)
589 unit_id = mkTupleCon 0
592 unit_ty = idType unit_id