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,
32 #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ <= 201
33 IMPORT_DELOOPER(DsLoop) ( match, matchSimply )
35 import {-# SOURCE #-} Match (match, matchSimply )
38 import HsSyn ( HsExpr(..), OutPat(..), HsLit(..), Fixity,
39 Match, HsBinds, Stmt, DoOrListComp, HsType, ArithSeqInfo )
40 import TcHsSyn ( SYN_IE(TypecheckedPat) )
41 import DsHsSyn ( outPatType, collectTypedPatBinders )
42 import CmdLineOpts ( opt_PprUserLength )
47 import CoreUtils ( coreExprType, mkCoreIfThenElse )
48 import PrelVals ( iRREFUT_PAT_ERROR_ID, voidId )
49 import Pretty ( Doc, hcat, text )
50 import Id ( idType, dataConArgTys,
52 SYN_IE(DataCon), SYN_IE(DictVar), SYN_IE(Id), GenId )
53 import Literal ( Literal(..) )
54 import PprType ( GenType, GenTyVar )
55 import PrimOp ( PrimOp )
56 import TyCon ( isNewTyCon, tyConDataCons )
57 import Type ( mkTyVarTys, mkRhoTy, mkForAllTys, mkFunTy,
58 mkTheta, isUnboxedType, applyTyCon, getAppTyCon,
59 GenType {- instances -}, SYN_IE(Type)
61 import TyVar ( GenTyVar {- instances -}, SYN_IE(TyVar) )
62 import TysPrim ( voidTy )
63 import TysWiredIn ( tupleTyCon, unitDataCon, tupleCon )
64 import UniqSet ( mkUniqSet, minusUniqSet, uniqSetToList, SYN_IE(UniqSet) )
65 import Util ( panic, assertPanic{-, pprTrace ToDo:rm-} )
66 import Unique ( Unique )
67 import Usage ( SYN_IE(UVar) )
68 import SrcLoc ( SrcLoc {- instance Outputable -} )
75 %************************************************************************
77 %* Selecting match variables
79 %************************************************************************
81 We're about to match against some patterns. We want to make some
82 @Ids@ to use as match variables. If a pattern has an @Id@ readily at
83 hand, which should indeed be bound to the pattern as a whole, then use it;
84 otherwise, make one up.
87 selectMatchVars :: [TypecheckedPat] -> DsM [Id]
89 = mapDs var_from_pat_maybe pats
91 var_from_pat_maybe (VarPat var) = returnDs var
92 var_from_pat_maybe (AsPat var pat) = returnDs var
93 var_from_pat_maybe (LazyPat pat) = var_from_pat_maybe pat
94 var_from_pat_maybe other_pat
95 = newSysLocalDs (outPatType other_pat) -- OK, better make up one...
99 %************************************************************************
101 %* type synonym EquationInfo and access functions for its pieces *
103 %************************************************************************
104 \subsection[EquationInfo-synonym]{@EquationInfo@: a useful synonym}
106 The ``equation info'' used by @match@ is relatively complicated and
107 worthy of a type synonym and a few handy functions.
112 [TypecheckedPat] -- the patterns for an eqn
113 MatchResult -- Encapsulates the guards and bindings
120 Type -- Type of argument expression
122 (CoreExpr -> CoreExpr)
123 -- Takes a expression to plug in at the
124 -- failure point(s). The expression should
127 DsMatchContext -- The context info is used when producing warnings
128 -- about shadowed patterns. It's the context
129 -- of the *first* thing matched in this group.
130 -- Should perhaps be a list of them all!
132 data CanItFail = CanFail | CantFail
134 orFail CantFail CantFail = CantFail
138 mkCoLetsMatchResult :: [CoreBinding] -> MatchResult -> MatchResult
139 mkCoLetsMatchResult binds (MatchResult can_it_fail ty body_fn cxt)
140 = MatchResult can_it_fail ty (\body -> mkCoLetsAny binds (body_fn body)) cxt
142 mkGuardedMatchResult :: CoreExpr -> MatchResult -> DsM MatchResult
143 mkGuardedMatchResult pred_expr (MatchResult can_it_fail ty body_fn cxt)
144 = returnDs (MatchResult CanFail
146 (\fail -> mkCoreIfThenElse pred_expr (body_fn fail) fail)
150 mkCoPrimCaseMatchResult :: Id -- Scrutinee
151 -> [(Literal, MatchResult)] -- Alternatives
153 mkCoPrimCaseMatchResult var alts
154 = newSysLocalDs (idType var) `thenDs` \ wild ->
155 returnDs (MatchResult CanFail
160 ((_,MatchResult _ ty1 _ cxt1) : _) = alts
162 mk_case alts wild fail_expr
163 = Case (Var var) (PrimAlts final_alts (BindDefault wild fail_expr))
165 final_alts = [ (lit, body_fn fail_expr)
166 | (lit, MatchResult _ _ body_fn _) <- alts
170 mkCoAlgCaseMatchResult :: Id -- Scrutinee
171 -> [(DataCon, [Id], MatchResult)] -- Alternatives
174 mkCoAlgCaseMatchResult var alts
175 | isNewTyCon tycon -- newtype case; use a let
176 = ASSERT( newtype_sanity )
177 returnDs (mkCoLetsMatchResult [coercion_bind] match_result)
179 | otherwise -- datatype case
180 = -- Find all the constructors in the type which aren't
181 -- explicitly mentioned in the alternatives:
182 case un_mentioned_constructors of
183 [] -> -- All constructors mentioned, so no default needed
184 returnDs (MatchResult can_any_alt_fail
186 (mk_case alts (\ignore -> NoDefault))
189 [con] -> -- Just one constructor missing, so add a case for it
190 -- We need to build new locals for the args of the constructor,
191 -- and figuring out their types is somewhat tiresome.
193 arg_tys = dataConArgTys con tycon_arg_tys
195 newSysLocalsDs arg_tys `thenDs` \ arg_ids ->
197 -- Now we are ready to construct the new alternative
199 new_alt = (con, arg_ids, MatchResult CanFail ty1 id NoMatchContext)
201 returnDs (MatchResult CanFail
203 (mk_case (new_alt:alts) (\ignore -> NoDefault))
206 other -> -- Many constructors missing, so use a default case
207 newSysLocalDs scrut_ty `thenDs` \ wild ->
208 returnDs (MatchResult CanFail
210 (mk_case alts (\fail_expr -> BindDefault wild fail_expr))
214 scrut_ty = idType var
215 (tycon, tycon_arg_tys) = --pprTrace "CoAlgCase:" (pprType PprDebug scrut_ty) $
219 (con_id, arg_ids, match_result) = head alts
220 arg_id = head arg_ids
221 coercion_bind = NonRec arg_id (Coerce (CoerceOut con_id)
224 newtype_sanity = null (tail alts) && null (tail arg_ids)
226 -- Stuff for data types
227 data_cons = tyConDataCons tycon
229 un_mentioned_constructors
230 = uniqSetToList (mkUniqSet data_cons `minusUniqSet` mkUniqSet [ con | (con, _, _) <- alts] )
232 match_results = [match_result | (_,_,match_result) <- alts]
233 (MatchResult _ ty1 _ cxt1 : _) = match_results
234 can_any_alt_fail = foldr1 orFail [can_it_fail | MatchResult can_it_fail _ _ _ <- match_results]
236 mk_case alts deflt_fn fail_expr
237 = Case (Var var) (AlgAlts final_alts (deflt_fn fail_expr))
239 final_alts = [ (con, args, body_fn fail_expr)
240 | (con, args, MatchResult _ _ body_fn _) <- alts
244 combineMatchResults :: MatchResult -> MatchResult -> DsM MatchResult
245 combineMatchResults (MatchResult CanFail ty1 body_fn1 cxt1)
246 (MatchResult can_it_fail2 ty2 body_fn2 cxt2)
247 = mkFailurePair ty1 `thenDs` \ (bind_fn, duplicatable_expr) ->
249 new_body_fn1 = \body1 -> Let (bind_fn body1) (body_fn1 duplicatable_expr)
250 new_body_fn2 = \body2 -> new_body_fn1 (body_fn2 body2)
252 returnDs (MatchResult can_it_fail2 ty1 new_body_fn2 cxt1)
254 combineMatchResults match_result1@(MatchResult CantFail ty body_fn1 cxt1)
256 = returnDs match_result1
259 -- The difference in combineGRHSMatchResults is that there is no
260 -- need to let-bind to avoid code duplication
261 combineGRHSMatchResults :: MatchResult -> MatchResult -> DsM MatchResult
262 combineGRHSMatchResults (MatchResult CanFail ty1 body_fn1 cxt1)
263 (MatchResult can_it_fail ty2 body_fn2 cxt2)
264 = returnDs (MatchResult can_it_fail ty1 (\ body -> body_fn1 (body_fn2 body)) cxt1)
266 combineGRHSMatchResults match_result1 match_result2
267 = -- Delegate to avoid duplication of code
268 combineMatchResults match_result1 match_result2
271 %************************************************************************
273 \subsection[dsExprToAtom]{Take an expression and produce an atom}
275 %************************************************************************
278 dsExprToAtom :: DsCoreArg -- The argument expression
279 -> (CoreArg -> DsM CoreExpr) -- Something taking the argument *atom*,
280 -- and delivering an expression E
281 -> DsM CoreExpr -- Either E or let x=arg-expr in E
283 dsExprToAtom (UsageArg u) continue_with = continue_with (UsageArg u)
284 dsExprToAtom (TyArg t) continue_with = continue_with (TyArg t)
285 dsExprToAtom (LitArg l) continue_with = continue_with (LitArg l)
287 dsExprToAtom (VarArg (Var v)) continue_with = continue_with (VarArg v)
288 dsExprToAtom (VarArg (Lit v)) continue_with = continue_with (LitArg v)
290 dsExprToAtom (VarArg arg_expr) continue_with
292 ty = coreExprType arg_expr
294 newSysLocalDs ty `thenDs` \ arg_id ->
295 continue_with (VarArg arg_id) `thenDs` \ body ->
298 then Case arg_expr (PrimAlts [] (BindDefault arg_id body))
299 else Let (NonRec arg_id arg_expr) body
302 dsExprsToAtoms :: [DsCoreArg]
303 -> ([CoreArg] -> DsM CoreExpr)
306 dsExprsToAtoms [] continue_with = continue_with []
308 dsExprsToAtoms (arg:args) continue_with
309 = dsExprToAtom arg $ \ arg_atom ->
310 dsExprsToAtoms args $ \ arg_atoms ->
311 continue_with (arg_atom:arg_atoms)
314 %************************************************************************
316 \subsection{Desugarer's versions of some Core functions}
318 %************************************************************************
321 type DsCoreArg = GenCoreArg CoreExpr{-NB!-} TyVar UVar
323 mkAppDs :: CoreExpr -> [DsCoreArg] -> DsM CoreExpr
324 mkConDs :: Id -> [DsCoreArg] -> DsM CoreExpr
325 mkPrimDs :: PrimOp -> [DsCoreArg] -> DsM CoreExpr
328 = dsExprsToAtoms args $ \ atoms ->
329 returnDs (mkGenApp fun atoms)
332 = dsExprsToAtoms args $ \ atoms ->
333 returnDs (Con con atoms)
336 = dsExprsToAtoms args $ \ atoms ->
337 returnDs (Prim op atoms)
341 showForErr :: Outputable a => a -> String -- Boring but useful
342 showForErr thing = show (ppr PprQuote thing)
344 mkErrorAppDs :: Id -- The error function
345 -> Type -- Type to which it should be applied
346 -> String -- The error message string to pass
349 mkErrorAppDs err_id ty msg
350 = getSrcLocDs `thenDs` \ src_loc ->
352 full_msg = show (hcat [ppr (PprForUser opt_PprUserLength) src_loc, text "|", text msg])
353 msg_lit = NoRepStr (_PK_ full_msg)
355 returnDs (mkApp (Var err_id) [] [ty] [LitArg msg_lit])
358 %************************************************************************
360 \subsection[mkSelectorBind]{Make a selector bind}
362 %************************************************************************
364 This is used in various places to do with lazy patterns.
365 For each binder $b$ in the pattern, we create a binding:
367 b = case v of pat' -> b'
369 where pat' is pat with each binder b cloned into b'.
371 ToDo: making these bindings should really depend on whether there's
372 much work to be done per binding. If the pattern is complex, it
373 should be de-mangled once, into a tuple (and then selected from).
374 Otherwise the demangling can be in-line in the bindings (as here).
376 Boring! Boring! One error message per binder. The above ToDo is
377 even more helpful. Something very similar happens for pattern-bound
381 mkSelectorBinds :: TypecheckedPat -- The pattern
382 -> CoreExpr -- Expression to which the pattern is bound
383 -> DsM [(Id,CoreExpr)]
385 mkSelectorBinds (VarPat v) val_expr
386 = returnDs [(v, val_expr)]
388 mkSelectorBinds pat val_expr
389 | is_simple_tuple_pat pat
390 = mkTupleBind binders val_expr
393 = mkErrorAppDs iRREFUT_PAT_ERROR_ID res_ty pat_string `thenDs` \ error_msg ->
394 matchSimply val_expr pat res_ty local_tuple error_msg `thenDs` \ tuple_expr ->
395 mkTupleBind binders tuple_expr
398 binders = collectTypedPatBinders pat
399 local_tuple = mkTupleExpr binders
400 res_ty = coreExprType local_tuple
402 is_simple_tuple_pat (TuplePat ps) = all is_var_pat ps
403 is_simple_tuple_pat other = False
405 is_var_pat (VarPat v) = True
406 is_var_pat other = False -- Even wild-card patterns aren't acceptable
408 pat_string = show (ppr (PprForUser opt_PprUserLength) pat)
413 mkTupleBind :: [Id] -- Names of tuple components
414 -> CoreExpr -- Expr whose value is a tuple of correct type
415 -> DsM [(Id, CoreExpr)] -- Bindings for the globals
418 mkTupleBind [local] tuple_expr
419 = returnDs [(local, tuple_expr)]
421 mkTupleBind locals tuple_expr
422 = newSysLocalDs (coreExprType tuple_expr) `thenDs` \ tuple_var ->
424 mk_bind local = (local, mkTupleSelector locals local (Var tuple_var))
426 returnDs ( (tuple_var, tuple_expr) :
431 @mkTupleExpr@ builds a tuple; the inverse to @mkTupleSelector@. If it
432 has only one element, it is the identity function.
434 mkTupleExpr :: [Id] -> CoreExpr
436 mkTupleExpr [] = Con unitDataCon []
437 mkTupleExpr [id] = Var id
438 mkTupleExpr ids = mkCon (tupleCon (length ids))
441 [ VarArg i | i <- ids ]
445 @mkTupleSelector@ builds a selector which scrutises the given
446 expression and extracts the one name from the list given.
447 If you want the no-shadowing rule to apply, the caller
448 is responsible for making sure that none of these names
451 If there is just one id in the ``tuple'', then the selector is
455 mkTupleSelector :: [Id] -- The tuple args
456 -> Id -- The selected one
457 -> CoreExpr -- Scrutinee
460 mkTupleSelector [] the_var scrut = panic "mkTupleSelector"
462 mkTupleSelector [var] should_be_the_same_var scrut
463 = ASSERT(var == should_be_the_same_var)
466 mkTupleSelector vars the_var scrut
467 = Case scrut (AlgAlts [(tupleCon arity, vars, Var the_var)]
474 %************************************************************************
476 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
478 %************************************************************************
480 Generally, we handle pattern matching failure like this: let-bind a
481 fail-variable, and use that variable if the thing fails:
483 let fail.33 = error "Help"
494 If the case can't fail, then there'll be no mention of fail.33, and the
495 simplifier will later discard it.
498 If it can fail in only one way, then the simplifier will inline it.
501 Only if it is used more than once will the let-binding remain.
504 There's a problem when the result of the case expression is of
505 unboxed type. Then the type of fail.33 is unboxed too, and
506 there is every chance that someone will change the let into a case:
512 which is of course utterly wrong. Rather than drop the condition that
513 only boxed types can be let-bound, we just turn the fail into a function
514 for the primitive case:
516 let fail.33 :: Void -> Int#
517 fail.33 = \_ -> error "Help"
526 Now fail.33 is a function, so it can be let-bound.
529 mkFailurePair :: Type -- Result type of the whole case expression
530 -> DsM (CoreExpr -> CoreBinding,
531 -- Binds the newly-created fail variable
532 -- to either the expression or \ _ -> expression
533 CoreExpr) -- Either the fail variable, or fail variable
534 -- applied to unit tuple
537 = newFailLocalDs (voidTy `mkFunTy` ty) `thenDs` \ fail_fun_var ->
538 newSysLocalDs voidTy `thenDs` \ fail_fun_arg ->
540 NonRec fail_fun_var (Lam (ValBinder fail_fun_arg) body),
541 App (Var fail_fun_var) (VarArg voidId))
544 = newFailLocalDs ty `thenDs` \ fail_var ->
545 returnDs (\ body -> NonRec fail_var body, Var fail_var)