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(..),
13 SYN_IE(EqnNo), SYN_IE(EqnSet),
15 combineGRHSMatchResults,
17 dsExprToAtomGivenTy, SYN_IE(DsCoreArg),
18 mkCoAlgCaseMatchResult,
19 mkAppDs, mkConDs, mkPrimDs, mkErrorAppDs,
21 mkCoPrimCaseMatchResult,
33 #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ <= 201
34 IMPORT_DELOOPER(DsLoop) ( match, matchSimply )
36 import {-# SOURCE #-} Match (match, matchSimply )
39 import HsSyn ( HsExpr(..), OutPat(..), HsLit(..), Fixity,
40 Match, HsBinds, Stmt, DoOrListComp, HsType, ArithSeqInfo )
41 import TcHsSyn ( SYN_IE(TypecheckedPat) )
42 import DsHsSyn ( outPatType, collectTypedPatBinders )
43 import CmdLineOpts ( opt_PprUserLength )
48 import CoreUtils ( coreExprType, mkCoreIfThenElse )
49 import PrelVals ( iRREFUT_PAT_ERROR_ID, voidId )
50 import Pretty ( Doc, hcat, text )
51 import Id ( idType, dataConArgTys,
53 SYN_IE(DataCon), SYN_IE(DictVar), SYN_IE(Id), GenId )
54 import Literal ( Literal(..) )
55 import PprType ( GenType, GenTyVar )
56 import PrimOp ( PrimOp )
57 import TyCon ( isNewTyCon, tyConDataCons )
58 import Type ( mkTyVarTys, mkRhoTy, mkForAllTys, mkFunTy,
59 mkTheta, isUnboxedType, applyTyCon, getAppTyCon,
60 GenType {- instances -}, SYN_IE(Type)
62 import TyVar ( GenTyVar {- instances -}, SYN_IE(TyVar) )
63 import TysPrim ( voidTy )
64 import TysWiredIn ( tupleTyCon, unitDataCon, tupleCon )
65 import UniqSet ( mkUniqSet, minusUniqSet, uniqSetToList, SYN_IE(UniqSet) )
66 import Util ( panic, assertPanic{-, pprTrace ToDo:rm-} )
67 import Unique ( Unique )
69 import Usage ( SYN_IE(UVar) )
70 import SrcLoc ( SrcLoc {- instance Outputable -} )
77 %************************************************************************
79 %* Selecting match variables
81 %************************************************************************
83 We're about to match against some patterns. We want to make some
84 @Ids@ to use as match variables. If a pattern has an @Id@ readily at
85 hand, which should indeed be bound to the pattern as a whole, then use it;
86 otherwise, make one up.
89 selectMatchVars :: [TypecheckedPat] -> DsM [Id]
91 = mapDs var_from_pat_maybe pats
93 var_from_pat_maybe (VarPat var) = returnDs var
94 var_from_pat_maybe (AsPat var pat) = returnDs var
95 var_from_pat_maybe (LazyPat pat) = var_from_pat_maybe pat
96 var_from_pat_maybe other_pat
97 = newSysLocalDs (outPatType other_pat) -- OK, better make up one...
101 %************************************************************************
103 %* type synonym EquationInfo and access functions for its pieces *
105 %************************************************************************
106 \subsection[EquationInfo-synonym]{@EquationInfo@: a useful synonym}
108 The ``equation info'' used by @match@ is relatively complicated and
109 worthy of a type synonym and a few handy functions.
114 type EqnSet = UniqSet EqnNo
118 EqnNo -- The number of the equation
119 DsMatchContext -- The context info is used when producing warnings
120 -- about shadowed patterns. It's the context
121 -- of the *first* thing matched in this group.
122 -- Should perhaps be a list of them all!
123 [TypecheckedPat] -- the patterns for an eqn
124 MatchResult -- Encapsulates the guards and bindings
131 Type -- Type of argument expression
133 (CoreExpr -> CoreExpr)
134 -- Takes a expression to plug in at the
135 -- failure point(s). The expression should
138 data CanItFail = CanFail | CantFail
140 orFail CantFail CantFail = CantFail
144 mkCoLetsMatchResult :: [CoreBinding] -> MatchResult -> MatchResult
145 mkCoLetsMatchResult binds (MatchResult can_it_fail ty body_fn)
146 = MatchResult can_it_fail ty (\body -> mkCoLetsAny binds (body_fn body))
148 mkGuardedMatchResult :: CoreExpr -> MatchResult -> DsM MatchResult
149 mkGuardedMatchResult pred_expr (MatchResult can_it_fail ty body_fn)
150 = returnDs (MatchResult CanFail
152 (\fail -> mkCoreIfThenElse pred_expr (body_fn fail) fail)
155 mkCoPrimCaseMatchResult :: Id -- Scrutinee
156 -> [(Literal, MatchResult)] -- Alternatives
158 mkCoPrimCaseMatchResult var alts
159 = newSysLocalDs (idType var) `thenDs` \ wild ->
160 returnDs (MatchResult CanFail
164 ((_,MatchResult _ ty1 _) : _) = alts
166 mk_case alts wild fail_expr
167 = Case (Var var) (PrimAlts final_alts (BindDefault wild fail_expr))
169 final_alts = [ (lit, body_fn fail_expr)
170 | (lit, MatchResult _ _ body_fn) <- alts
174 mkCoAlgCaseMatchResult :: Id -- Scrutinee
175 -> [(DataCon, [Id], MatchResult)] -- Alternatives
178 mkCoAlgCaseMatchResult var alts
179 | isNewTyCon tycon -- newtype case; use a let
180 = ASSERT( newtype_sanity )
181 returnDs (mkCoLetsMatchResult [coercion_bind] match_result)
183 | otherwise -- datatype case
184 = -- Find all the constructors in the type which aren't
185 -- explicitly mentioned in the alternatives:
186 case un_mentioned_constructors of
187 [] -> -- All constructors mentioned, so no default needed
188 returnDs (MatchResult can_any_alt_fail
190 (mk_case alts (\ignore -> NoDefault)))
192 [con] -> -- Just one constructor missing, so add a case for it
193 -- We need to build new locals for the args of the constructor,
194 -- and figuring out their types is somewhat tiresome.
196 arg_tys = dataConArgTys con tycon_arg_tys
198 newSysLocalsDs arg_tys `thenDs` \ arg_ids ->
200 -- Now we are ready to construct the new alternative
202 new_alt = (con, arg_ids, MatchResult CanFail ty1 id)
204 returnDs (MatchResult CanFail
206 (mk_case (new_alt:alts) (\ignore -> NoDefault)))
208 other -> -- Many constructors missing, so use a default case
209 newSysLocalDs scrut_ty `thenDs` \ wild ->
210 returnDs (MatchResult CanFail
212 (mk_case alts (\fail_expr -> BindDefault wild fail_expr)))
215 scrut_ty = idType var
216 (tycon, tycon_arg_tys) = --pprTrace "CoAlgCase:" (pprType PprDebug scrut_ty) $
220 (con_id, arg_ids, match_result) = head alts
221 arg_id = head arg_ids
222 coercion_bind = NonRec arg_id (Coerce (CoerceOut con_id)
225 newtype_sanity = null (tail alts) && null (tail arg_ids)
227 -- Stuff for data types
228 data_cons = tyConDataCons tycon
230 un_mentioned_constructors
231 = uniqSetToList (mkUniqSet data_cons `minusUniqSet` mkUniqSet [ con | (con, _, _) <- alts] )
233 match_results = [match_result | (_,_,match_result) <- alts]
234 (MatchResult _ ty1 _ : _) = match_results
235 can_any_alt_fail = foldr1 orFail [can_it_fail | MatchResult can_it_fail _ _ <- match_results]
237 mk_case alts deflt_fn fail_expr
238 = Case (Var var) (AlgAlts final_alts (deflt_fn fail_expr))
240 final_alts = [ (con, args, body_fn fail_expr)
241 | (con, args, MatchResult _ _ body_fn) <- alts
245 combineMatchResults :: MatchResult -> MatchResult -> DsM MatchResult
246 combineMatchResults (MatchResult CanFail ty1 body_fn1)
247 (MatchResult can_it_fail2 ty2 body_fn2)
248 = mkFailurePair ty1 `thenDs` \ (bind_fn, duplicatable_expr) ->
250 new_body_fn1 = \body1 -> Let (bind_fn body1) (body_fn1 duplicatable_expr)
251 new_body_fn2 = \body2 -> new_body_fn1 (body_fn2 body2)
253 returnDs (MatchResult can_it_fail2 ty1 new_body_fn2)
255 combineMatchResults match_result1@(MatchResult CantFail ty body_fn1)
257 = returnDs match_result1
260 -- The difference in combineGRHSMatchResults is that there is no
261 -- need to let-bind to avoid code duplication
262 combineGRHSMatchResults :: MatchResult -> MatchResult -> DsM MatchResult
263 combineGRHSMatchResults (MatchResult CanFail ty1 body_fn1)
264 (MatchResult can_it_fail ty2 body_fn2)
265 = returnDs (MatchResult can_it_fail ty1 (\ body -> body_fn1 (body_fn2 body)))
267 combineGRHSMatchResults match_result1 match_result2
268 = -- Delegate to avoid duplication of code
269 combineMatchResults match_result1 match_result2
272 %************************************************************************
274 \subsection[dsExprToAtom]{Take an expression and produce an atom}
276 %************************************************************************
279 dsArgToAtom :: DsCoreArg -- The argument expression
280 -> (CoreArg -> DsM CoreExpr) -- Something taking the argument *atom*,
281 -- and delivering an expression E
282 -> DsM CoreExpr -- Either E or let x=arg-expr in E
284 dsArgToAtom (UsageArg u) continue_with = continue_with (UsageArg u)
285 dsArgToAtom (TyArg t) continue_with = continue_with (TyArg t)
286 dsArgToAtom (LitArg l) continue_with = continue_with (LitArg l)
287 dsArgToAtom (VarArg arg) continue_with = dsExprToAtomGivenTy arg (coreExprType arg) continue_with
290 :: CoreExpr -- The argument expression
291 -> Type -- Type of the argument
292 -> (CoreArg -> DsM CoreExpr) -- Something taking the argument *atom*,
293 -- and delivering an expression E
294 -> DsM CoreExpr -- Either E or let x=arg-expr in E
296 dsExprToAtomGivenTy (Var v) arg_ty continue_with = continue_with (VarArg v)
297 dsExprToAtomGivenTy (Lit v) arg_ty continue_with = continue_with (LitArg v)
298 dsExprToAtomGivenTy arg_expr arg_ty continue_with
299 = newSysLocalDs arg_ty `thenDs` \ arg_id ->
300 continue_with (VarArg arg_id) `thenDs` \ body ->
302 if isUnboxedType arg_ty
303 then Case arg_expr (PrimAlts [] (BindDefault arg_id body))
304 else Let (NonRec arg_id arg_expr) body
307 dsArgsToAtoms :: [DsCoreArg]
308 -> ([CoreArg] -> DsM CoreExpr)
311 dsArgsToAtoms [] continue_with = continue_with []
313 dsArgsToAtoms (arg:args) continue_with
314 = dsArgToAtom arg $ \ arg_atom ->
315 dsArgsToAtoms args $ \ arg_atoms ->
316 continue_with (arg_atom:arg_atoms)
319 %************************************************************************
321 \subsection{Desugarer's versions of some Core functions}
323 %************************************************************************
326 type DsCoreArg = GenCoreArg CoreExpr{-NB!-} TyVar UVar
328 mkAppDs :: CoreExpr -> [DsCoreArg] -> DsM CoreExpr
329 mkConDs :: Id -> [DsCoreArg] -> DsM CoreExpr
330 mkPrimDs :: PrimOp -> [DsCoreArg] -> DsM CoreExpr
333 = dsArgsToAtoms args $ \ atoms ->
334 returnDs (mkGenApp fun atoms)
337 = dsArgsToAtoms args $ \ atoms ->
338 returnDs (Con con atoms)
341 = dsArgsToAtoms args $ \ atoms ->
342 returnDs (Prim op atoms)
346 showForErr :: Outputable a => a -> String -- Boring but useful
347 showForErr thing = show (ppr PprQuote thing)
349 mkErrorAppDs :: Id -- The error function
350 -> Type -- Type to which it should be applied
351 -> String -- The error message string to pass
354 mkErrorAppDs err_id ty msg
355 = getSrcLocDs `thenDs` \ src_loc ->
357 full_msg = show (hcat [ppr (PprForUser opt_PprUserLength) src_loc, text "|", text msg])
358 msg_lit = NoRepStr (_PK_ full_msg)
360 returnDs (mkApp (Var err_id) [] [ty] [LitArg msg_lit])
363 %************************************************************************
365 \subsection[mkSelectorBind]{Make a selector bind}
367 %************************************************************************
369 This is used in various places to do with lazy patterns.
370 For each binder $b$ in the pattern, we create a binding:
372 b = case v of pat' -> b'
374 where pat' is pat with each binder b cloned into b'.
376 ToDo: making these bindings should really depend on whether there's
377 much work to be done per binding. If the pattern is complex, it
378 should be de-mangled once, into a tuple (and then selected from).
379 Otherwise the demangling can be in-line in the bindings (as here).
381 Boring! Boring! One error message per binder. The above ToDo is
382 even more helpful. Something very similar happens for pattern-bound
386 mkSelectorBinds :: TypecheckedPat -- The pattern
387 -> CoreExpr -- Expression to which the pattern is bound
388 -> DsM [(Id,CoreExpr)]
390 mkSelectorBinds (VarPat v) val_expr
391 = returnDs [(v, val_expr)]
393 mkSelectorBinds pat val_expr
394 | is_simple_tuple_pat pat
395 = mkTupleBind binders val_expr
398 = mkErrorAppDs iRREFUT_PAT_ERROR_ID res_ty pat_string `thenDs` \ error_expr ->
399 matchSimply val_expr LetMatch pat res_ty local_tuple error_expr `thenDs` \ tuple_expr ->
400 mkTupleBind binders tuple_expr
403 binders = collectTypedPatBinders pat
404 local_tuple = mkTupleExpr binders
405 res_ty = coreExprType local_tuple
407 is_simple_tuple_pat (TuplePat ps) = all is_var_pat ps
408 is_simple_tuple_pat other = False
410 is_var_pat (VarPat v) = True
411 is_var_pat other = False -- Even wild-card patterns aren't acceptable
413 pat_string = show (ppr (PprForUser opt_PprUserLength) pat)
418 mkTupleBind :: [Id] -- Names of tuple components
419 -> CoreExpr -- Expr whose value is a tuple of correct type
420 -> DsM [(Id, CoreExpr)] -- Bindings for the globals
423 mkTupleBind [local] tuple_expr
424 = returnDs [(local, tuple_expr)]
426 mkTupleBind locals tuple_expr
427 = newSysLocalDs (coreExprType tuple_expr) `thenDs` \ tuple_var ->
429 mk_bind local = (local, mkTupleSelector locals local (Var tuple_var))
431 returnDs ( (tuple_var, tuple_expr) :
436 @mkTupleExpr@ builds a tuple; the inverse to @mkTupleSelector@. If it
437 has only one element, it is the identity function.
439 mkTupleExpr :: [Id] -> CoreExpr
441 mkTupleExpr [] = Con unitDataCon []
442 mkTupleExpr [id] = Var id
443 mkTupleExpr ids = mkCon (tupleCon (length ids))
446 [ VarArg 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 :: [Id] -- The tuple args
461 -> Id -- The selected one
462 -> CoreExpr -- Scrutinee
465 mkTupleSelector [] the_var scrut = panic "mkTupleSelector"
467 mkTupleSelector [var] should_be_the_same_var scrut
468 = ASSERT(var == should_be_the_same_var)
471 mkTupleSelector vars the_var scrut
472 = Case scrut (AlgAlts [(tupleCon arity, vars, Var 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 :: Void -> Int#
522 fail.33 = \_ -> error "Help"
531 Now fail.33 is a function, so it can be let-bound.
534 mkFailurePair :: Type -- Result type of the whole case expression
535 -> DsM (CoreExpr -> CoreBinding,
536 -- Binds the newly-created fail variable
537 -- to either the expression or \ _ -> expression
538 CoreExpr) -- Either the fail variable, or fail variable
539 -- applied to unit tuple
542 = newFailLocalDs (voidTy `mkFunTy` ty) `thenDs` \ fail_fun_var ->
543 newSysLocalDs voidTy `thenDs` \ fail_fun_arg ->
545 NonRec fail_fun_var (Lam (ValBinder fail_fun_arg) body),
546 App (Var fail_fun_var) (VarArg voidId))
549 = newFailLocalDs ty `thenDs` \ fail_var ->
550 returnDs (\ body -> NonRec fail_var body, Var fail_var)