2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[CoreRules]{Transformation rules}
8 RuleBase, emptyRuleBase, mkRuleBase, extendRuleBaseList,
9 unionRuleBase, pprRuleBase, ruleCheckProgram,
11 mkSpecInfo, extendSpecInfo, addSpecInfo,
12 rulesOfBinds, addIdSpecialisations,
16 lookupRule, mkLocalRule, roughTopNames
19 #include "HsVersions.h"
21 import CoreSyn -- All of it
22 import OccurAnal ( occurAnalyseExpr )
23 import CoreFVs ( exprFreeVars, exprsFreeVars, bindFreeVars, rulesRhsFreeVars )
24 import CoreUnfold ( isCheapUnfolding, unfoldingTemplate )
25 import CoreUtils ( tcEqExprX )
26 import PprCore ( pprRules )
27 import Type ( TvSubstEnv )
28 import Coercion ( coercionKind )
29 import TcType ( tcSplitTyConApp_maybe )
30 import CoreTidy ( tidyRules )
31 import Id ( Id, idUnfolding, isLocalId, isGlobalId, idName,
32 idSpecialisation, idCoreRules, setIdSpecialisation )
33 import IdInfo ( SpecInfo( SpecInfo ) )
35 import VarEnv ( IdEnv, InScopeSet, emptyTidyEnv,
36 emptyInScopeSet, mkInScopeSet, extendInScopeSetList,
37 emptyVarEnv, lookupVarEnv, extendVarEnv,
38 nukeRnEnvL, mkRnEnv2, rnOccR, rnOccL, inRnEnvR,
39 rnBndrR, rnBndr2, rnBndrL, rnBndrs2,
40 rnInScope, extendRnInScopeList, lookupRnInScope )
42 import Name ( Name, NamedThing(..), nameOccName )
44 import Unify ( ruleMatchTyX, MatchEnv(..) )
45 import BasicTypes ( Activation, CompilerPhase, isActive )
48 import Maybes ( isJust, orElse )
51 import Util ( singleton )
52 import List ( isPrefixOf )
56 %************************************************************************
58 \subsection[specialisation-IdInfo]{Specialisation info about an @Id@}
60 %************************************************************************
62 A @CoreRule@ holds details of one rule for an @Id@, which
63 includes its specialisations.
65 For example, if a rule for @f@ contains the mapping:
67 forall a b d. [Type (List a), Type b, Var d] ===> f' a b
69 then when we find an application of f to matching types, we simply replace
70 it by the matching RHS:
72 f (List Int) Bool dict ===> f' Int Bool
74 All the stuff about how many dictionaries to discard, and what types
75 to apply the specialised function to, are handled by the fact that the
76 Rule contains a template for the result of the specialisation.
78 There is one more exciting case, which is dealt with in exactly the same
79 way. If the specialised value is unboxed then it is lifted at its
80 definition site and unlifted at its uses. For example:
82 pi :: forall a. Num a => a
84 might have a specialisation
86 [Int#] ===> (case pi' of Lift pi# -> pi#)
88 where pi' :: Lift Int# is the specialised version of pi.
91 mkLocalRule :: RuleName -> Activation
92 -> Name -> [CoreBndr] -> [CoreExpr] -> CoreExpr -> CoreRule
93 -- Used to make CoreRule for an Id defined in this module
94 mkLocalRule name act fn bndrs args rhs
95 = Rule { ru_name = name, ru_fn = fn, ru_act = act,
96 ru_bndrs = bndrs, ru_args = args,
97 ru_rhs = rhs, ru_rough = roughTopNames args,
98 ru_orph = Just (nameOccName fn), ru_local = True }
101 roughTopNames :: [CoreExpr] -> [Maybe Name]
102 roughTopNames args = map roughTopName args
104 roughTopName :: CoreExpr -> Maybe Name
105 -- Find the "top" free name of an expression
106 -- a) the function in an App chain (if a GlobalId)
107 -- b) the TyCon in a type
108 -- This is used for the fast-match-check for rules;
109 -- if the top names don't match, the rest can't
110 roughTopName (Type ty) = case tcSplitTyConApp_maybe ty of
111 Just (tc,_) -> Just (getName tc)
113 roughTopName (App f a) = roughTopName f
114 roughTopName (Var f) | isGlobalId f = Just (idName f)
115 | otherwise = Nothing
116 roughTopName other = Nothing
118 ruleCantMatch :: [Maybe Name] -> [Maybe Name] -> Bool
119 -- (ruleCantMatch tpl actual) returns True only if 'actual'
120 -- definitely can't match 'tpl' by instantiating 'tpl'.
121 -- It's only a one-way match; unlike instance matching we
122 -- don't consider unification
124 -- Notice that there is no case
125 -- ruleCantMatch (Just n1 : ts) (Nothing : as) = True
126 -- Reason: a local variable 'v' in the actuals might
127 -- have an unfolding which is a global.
128 -- This quite often happens with case scrutinees.
129 ruleCantMatch (Just n1 : ts) (Just n2 : as) = n1 /= n2 || ruleCantMatch ts as
130 ruleCantMatch (t : ts) (a : as) = ruleCantMatch ts as
131 ruleCantMatch ts as = False
135 %************************************************************************
137 SpecInfo: the rules in an IdInfo
139 %************************************************************************
142 mkSpecInfo :: [CoreRule] -> SpecInfo
143 mkSpecInfo rules = SpecInfo rules (rulesRhsFreeVars rules)
145 extendSpecInfo :: SpecInfo -> [CoreRule] -> SpecInfo
146 extendSpecInfo (SpecInfo rs1 fvs1) rs2
147 = SpecInfo (rs2 ++ rs1) (rulesRhsFreeVars rs2 `unionVarSet` fvs1)
149 addSpecInfo :: SpecInfo -> SpecInfo -> SpecInfo
150 addSpecInfo (SpecInfo rs1 fvs1) (SpecInfo rs2 fvs2)
151 = SpecInfo (rs1 ++ rs2) (fvs1 `unionVarSet` fvs2)
153 addIdSpecialisations :: Id -> [CoreRule] -> Id
154 addIdSpecialisations id rules
155 = setIdSpecialisation id $
156 extendSpecInfo (idSpecialisation id) rules
158 rulesOfBinds :: [CoreBind] -> [CoreRule]
159 rulesOfBinds binds = concatMap (concatMap idCoreRules . bindersOf) binds
163 %************************************************************************
167 %************************************************************************
170 type RuleBase = NameEnv [CoreRule]
171 -- Maps (the name of) an Id to its rules
172 -- The rules are are unordered;
173 -- we sort out any overlaps on lookup
175 emptyRuleBase = emptyNameEnv
177 mkRuleBase :: [CoreRule] -> RuleBase
178 mkRuleBase rules = extendRuleBaseList emptyRuleBase rules
180 extendRuleBaseList :: RuleBase -> [CoreRule] -> RuleBase
181 extendRuleBaseList rule_base new_guys
182 = foldl extendRuleBase rule_base new_guys
184 unionRuleBase :: RuleBase -> RuleBase -> RuleBase
185 unionRuleBase rb1 rb2 = plusNameEnv_C (++) rb1 rb2
187 extendRuleBase :: RuleBase -> CoreRule -> RuleBase
188 extendRuleBase rule_base rule
189 = extendNameEnv_Acc (:) singleton rule_base (ruleIdName rule) rule
191 pprRuleBase :: RuleBase -> SDoc
192 pprRuleBase rules = vcat [ pprRules (tidyRules emptyTidyEnv rs)
193 | rs <- nameEnvElts rules ]
197 %************************************************************************
199 \subsection{Matching}
201 %************************************************************************
204 lookupRule :: (Activation -> Bool) -> InScopeSet
205 -> RuleBase -- Imported rules
206 -> Id -> [CoreExpr] -> Maybe (RuleName, CoreExpr)
207 lookupRule is_active in_scope rule_base fn args
208 = matchRules is_active in_scope fn args rules
210 -- The rules for an Id come from two places:
211 -- (a) the ones it is born with (idCoreRules fn)
212 -- (b) rules added in subsequent modules (extra_rules)
213 -- PrimOps, for example, are born with a bunch of rules under (a)
214 rules = extra_rules ++ idCoreRules fn
215 extra_rules | isLocalId fn = []
216 | otherwise = lookupNameEnv rule_base (idName fn) `orElse` []
218 matchRules :: (Activation -> Bool) -> InScopeSet
220 -> [CoreRule] -> Maybe (RuleName, CoreExpr)
221 -- See comments on matchRule
222 matchRules is_active in_scope fn args rules
223 = case go [] rules of
225 (m:ms) -> Just (case findBest (fn,args) m ms of
226 (rule, ans) -> (ru_name rule, ans))
228 rough_args = map roughTopName args
230 go :: [(CoreRule,CoreExpr)] -> [CoreRule] -> [(CoreRule,CoreExpr)]
232 go ms (r:rs) = case (matchRule is_active in_scope args rough_args r) of
233 Just e -> go ((r,e):ms) rs
236 findBest :: (Id, [CoreExpr])
237 -> (CoreRule,CoreExpr) -> [(CoreRule,CoreExpr)] -> (CoreRule,CoreExpr)
238 -- All these pairs matched the expression
239 -- Return the pair the the most specific rule
240 -- The (fn,args) is just for overlap reporting
242 findBest target (rule,ans) [] = (rule,ans)
243 findBest target (rule1,ans1) ((rule2,ans2):prs)
244 | rule1 `isMoreSpecific` rule2 = findBest target (rule1,ans1) prs
245 | rule2 `isMoreSpecific` rule1 = findBest target (rule2,ans2) prs
247 | otherwise = pprTrace "Rules.findBest: rule overlap (Rule 1 wins)"
248 (vcat [ptext SLIT("Expression to match:") <+> ppr fn <+> sep (map ppr args),
249 ptext SLIT("Rule 1:") <+> ppr rule1,
250 ptext SLIT("Rule 2:") <+> ppr rule2]) $
251 findBest target (rule1,ans1) prs
253 | otherwise = findBest target (rule1,ans1) prs
258 isMoreSpecific :: CoreRule -> CoreRule -> Bool
259 isMoreSpecific (BuiltinRule {}) r2 = True
260 isMoreSpecific r1 (BuiltinRule {}) = False
261 isMoreSpecific (Rule { ru_bndrs = bndrs1, ru_args = args1 })
262 (Rule { ru_bndrs = bndrs2, ru_args = args2 })
263 = isJust (matchN in_scope bndrs2 args2 args1)
265 in_scope = mkInScopeSet (mkVarSet bndrs1)
266 -- Actually we should probably include the free vars
267 -- of rule1's args, but I can't be bothered
269 noBlackList :: Activation -> Bool
270 noBlackList act = False -- Nothing is black listed
272 matchRule :: (Activation -> Bool) -> InScopeSet
273 -> [CoreExpr] -> [Maybe Name]
274 -> CoreRule -> Maybe CoreExpr
276 -- If (matchRule rule args) returns Just (name,rhs)
277 -- then (f args) matches the rule, and the corresponding
278 -- rewritten RHS is rhs
280 -- The bndrs and rhs is occurrence-analysed
285 -- forall f g x. map f (map g x) ==> map (f . g) x
287 -- CoreRule "map/map"
288 -- [f,g,x] -- tpl_vars
289 -- [f,map g x] -- tpl_args
290 -- map (f.g) x) -- rhs
292 -- Then the call: matchRule the_rule [e1,map e2 e3]
293 -- = Just ("map/map", (\f,g,x -> rhs) e1 e2 e3)
295 -- Any 'surplus' arguments in the input are simply put on the end
298 matchRule is_active in_scope args rough_args
299 (BuiltinRule { ru_name = name, ru_try = match_fn })
300 = case match_fn args of
301 Just expr -> Just expr
304 matchRule is_active in_scope args rough_args
305 (Rule { ru_name = rn, ru_act = act, ru_rough = tpl_tops,
306 ru_bndrs = tpl_vars, ru_args = tpl_args,
308 | not (is_active act) = Nothing
309 | ruleCantMatch tpl_tops rough_args = Nothing
311 = case matchN in_scope tpl_vars tpl_args args of
313 Just (binds, tpl_vals, leftovers) -> Just (mkLets binds $
318 rule_fn = occurAnalyseExpr (mkLams tpl_vars rhs)
319 -- We could do this when putting things into the rulebase, I guess
324 -> [Var] -- Template tyvars
325 -> [CoreExpr] -- Template
326 -> [CoreExpr] -- Target; can have more elts than template
327 -> Maybe ([CoreBind], -- Bindings to wrap around the entire result
328 [CoreExpr], -- What is substituted for each template var
329 [CoreExpr]) -- Leftover target exprs
331 matchN in_scope tmpl_vars tmpl_es target_es
332 = do { ((tv_subst, id_subst, binds), leftover_es)
333 <- go init_menv emptySubstEnv tmpl_es target_es
334 ; return (fromOL binds,
335 map (lookup_tmpl tv_subst id_subst) tmpl_vars,
338 init_menv = ME { me_tmpls = mkVarSet tmpl_vars, me_env = init_rn_env }
339 init_rn_env = mkRnEnv2 (extendInScopeSetList in_scope tmpl_vars)
341 go menv subst [] es = Just (subst, es)
342 go menv subst ts [] = Nothing -- Fail if too few actual args
343 go menv subst (t:ts) (e:es) = do { subst1 <- match menv subst t e
344 ; go menv subst1 ts es }
346 lookup_tmpl :: TvSubstEnv -> IdSubstEnv -> Var -> CoreExpr
347 lookup_tmpl tv_subst id_subst tmpl_var
348 | isTyVar tmpl_var = case lookupVarEnv tv_subst tmpl_var of
350 Nothing -> unbound tmpl_var
351 | otherwise = case lookupVarEnv id_subst tmpl_var of
353 other -> unbound tmpl_var
355 unbound var = pprPanic "Template variable unbound in rewrite rule" (ppr var)
359 ---------------------------------------------
360 The inner workings of matching
361 ---------------------------------------------
364 -- These two definitions are not the same as in Subst,
365 -- but they simple and direct, and purely local to this module
367 -- * The domain of the TvSubstEnv and IdSubstEnv are the template
368 -- variables passed into the match.
370 -- * The (OrdList CoreBind) in a SubstEnv are the bindings floated out
371 -- from nested matches; see the Let case of match, below
373 type SubstEnv = (TvSubstEnv, IdSubstEnv, OrdList CoreBind)
374 type IdSubstEnv = IdEnv CoreExpr
376 emptySubstEnv :: SubstEnv
377 emptySubstEnv = (emptyVarEnv, emptyVarEnv, nilOL)
380 -- At one stage I tried to match even if there are more
381 -- template args than real args.
383 -- I now think this is probably a bad idea.
384 -- Should the template (map f xs) match (map g)? I think not.
385 -- For a start, in general eta expansion wastes work.
391 -> CoreExpr -- Template
392 -> CoreExpr -- Target
395 -- See the notes with Unify.match, which matches types
396 -- Everything is very similar for terms
398 -- Interesting examples:
400 -- \x->f against \f->f
401 -- When we meet the lambdas we must remember to rename f to f' in the
402 -- second expresion. The RnEnv2 does that.
405 -- forall a. \b->b against \a->3
406 -- We must rename the \a. Otherwise when we meet the lambdas we
407 -- might substitute [a/b] in the template, and then erroneously
408 -- succeed in matching what looks like the template variable 'a' against 3.
410 -- The Var case follows closely what happens in Unify.match
411 match menv subst (Var v1) e2
412 | Just subst <- match_var menv subst v1 e2
415 -- Here is another important rule: if the term being matched is a
416 -- variable, we expand it so long as its unfolding is a WHNF
417 -- (Its occurrence information is not necessarily up to date,
418 -- so we don't use it.)
419 match menv subst e1 (Var v2)
420 | not (inRnEnvR rn_env v2),
421 -- If v2 is in the RnEnvR, then it's locally bound and can't
422 -- have an unfolding. We must make this check because if it
423 -- is locally bound we must not look it up in the in-scope set
424 -- E.g. (\x->x) where x is already in scope
425 isCheapUnfolding unfolding
426 = match menv subst e1 (unfoldingTemplate unfolding)
429 unfolding = idUnfolding (lookupRnInScope rn_env v2)
430 -- Notice that we look up v2 in the in-scope set
431 -- See Note [Lookup in-scope]
433 -- Matching a let-expression. Consider
434 -- RULE forall x. f (g x) = <rhs>
435 -- and target expression
436 -- f (let { w=R } in g E))
437 -- Then we'd like the rule to match, to generate
438 -- let { w=R } in (\x. <rhs>) E
439 -- In effect, we want to float the let-binding outward, to enable
440 -- the match to happen. This is the WHOLE REASON for accumulating
441 -- bindings in the SubstEnv
443 -- We can only do this if
444 -- (a) Widening the scope of w does not capture any variables
445 -- We use a conservative test: w is not already in scope
446 -- (b) The free variables of R are not bound by the part of the
447 -- target expression outside the let binding; e.g.
448 -- f (\v. let w = v+1 in g E)
449 -- Here we obviously cannot float the let-binding for w.
451 match menv subst@(tv_subst, id_subst, binds) e1 (Let bind e2)
452 | all freshly_bound bndrs,
453 not (any locally_bound bind_fvs)
454 = match (menv { me_env = rn_env' })
455 (tv_subst, id_subst, binds `snocOL` bind)
459 bndrs = bindersOf bind
460 bind_fvs = varSetElems (bindFreeVars bind)
461 freshly_bound x = not (x `rnInScope` rn_env)
462 locally_bound x = inRnEnvR rn_env x
463 rn_env' = extendRnInScopeList rn_env bndrs
465 match menv subst (Lit lit1) (Lit lit2)
469 match menv subst (App f1 a1) (App f2 a2)
470 = do { subst' <- match menv subst f1 f2
471 ; match menv subst' a1 a2 }
473 match menv subst (Lam x1 e1) (Lam x2 e2)
474 = match menv' subst e1 e2
476 menv' = menv { me_env = rnBndr2 (me_env menv) x1 x2 }
478 -- This rule does eta expansion
479 -- (\x.M) ~ N iff M ~ N x
480 -- It's important that this is *after* the let rule,
481 -- so that (\x.M) ~ (let y = e in \y.N)
482 -- does the let thing, and then gets the lam/lam rule above
483 match menv subst (Lam x1 e1) e2
484 = match menv' subst e1 (App e2 (varToCoreExpr new_x))
486 (rn_env', new_x) = rnBndrL (me_env menv) x1
487 menv' = menv { me_env = rn_env' }
489 -- Eta expansion the other way
490 -- M ~ (\y.N) iff M y ~ N
491 match menv subst e1 (Lam x2 e2)
492 = match menv' subst (App e1 (varToCoreExpr new_x)) e2
494 (rn_env', new_x) = rnBndrR (me_env menv) x2
495 menv' = menv { me_env = rn_env' }
497 match menv subst (Case e1 x1 ty1 alts1) (Case e2 x2 ty2 alts2)
498 = do { subst1 <- match_ty menv subst ty1 ty2
499 ; subst2 <- match menv subst1 e1 e2
500 ; let menv' = menv { me_env = rnBndr2 (me_env menv) x1 x2 }
501 ; match_alts menv' subst2 alts1 alts2 -- Alts are both sorted
504 match menv subst (Type ty1) (Type ty2)
505 = match_ty menv subst ty1 ty2
507 match menv subst (Cast e1 co1) (Cast e2 co2)
508 | (from1, to1) <- coercionKind co1
509 , (from2, to2) <- coercionKind co2
510 = do { subst1 <- match_ty menv subst to1 to2
511 ; subst2 <- match_ty menv subst1 from1 from2
512 ; match menv subst2 e1 e2 }
514 {- REMOVING OLD CODE: I think that the above handling for let is
515 better than the stuff here, which looks
516 pretty suspicious to me. SLPJ Sept 06
517 -- This is an interesting rule: we simply ignore lets in the
518 -- term being matched against! The unfolding inside it is (by assumption)
519 -- already inside any occurrences of the bound variables, so we'll expand
520 -- them when we encounter them. This gives a chance of matching
521 -- forall x,y. f (g (x,y))
523 -- f (let v = (a,b) in g v)
525 match menv subst e1 (Let bind e2)
526 = match (menv { me_env = rn_env' }) subst e1 e2
528 (rn_env', _bndrs') = mapAccumL rnBndrR (me_env menv) (bindersOf bind)
529 -- It's important to do this renaming, so that the bndrs
530 -- are brought into the local scope. For example:
532 -- forall f,x,xs. f (x:xs)
534 -- f (let y = e in (y:[]))
535 -- We must not get success with x->y! So we record that y is
536 -- locally bound (with rnBndrR), and proceed. The Var case
537 -- will fail when trying to bind x->y
540 -- Everything else fails
541 match menv subst e1 e2 = Nothing
543 ------------------------------------------
544 match_var :: MatchEnv
547 -> CoreExpr -- Target
549 match_var menv subst@(tv_subst, id_subst, binds) v1 e2
550 | v1' `elemVarSet` me_tmpls menv
551 = case lookupVarEnv id_subst v1' of
552 Nothing | any (inRnEnvR rn_env) (varSetElems (exprFreeVars e2))
553 -> Nothing -- Occurs check failure
554 -- e.g. match forall a. (\x-> a x) against (\y. y y)
556 | otherwise -- No renaming to do on e2
557 -> Just (tv_subst, extendVarEnv id_subst v1 e2, binds)
559 Just e2' | tcEqExprX (nukeRnEnvL rn_env) e2' e2
565 | otherwise -- v1 is not a template variable; check for an exact match with e2
567 Var v2 | v1' == rnOccR rn_env v2 -> Just subst
572 v1' = rnOccL rn_env v1
573 -- If the template is
574 -- forall x. f x (\x -> x) = ...
575 -- Then the x inside the lambda isn't the
576 -- template x, so we must rename first!
579 ------------------------------------------
580 match_alts :: MatchEnv
582 -> [CoreAlt] -- Template
583 -> [CoreAlt] -- Target
585 match_alts menv subst [] []
587 match_alts menv subst ((c1,vs1,r1):alts1) ((c2,vs2,r2):alts2)
589 = do { subst1 <- match menv' subst r1 r2
590 ; match_alts menv subst1 alts1 alts2 }
593 menv' = menv { me_env = rnBndrs2 (me_env menv) vs1 vs2 }
595 match_alts menv subst alts1 alts2
599 Matching Core types: use the matcher in TcType.
600 Notice that we treat newtypes as opaque. For example, suppose
601 we have a specialised version of a function at a newtype, say
603 We only want to replace (f T) with f', not (f Int).
606 ------------------------------------------
607 match_ty menv (tv_subst, id_subst, binds) ty1 ty2
608 = do { tv_subst' <- Unify.ruleMatchTyX menv tv_subst ty1 ty2
609 ; return (tv_subst', id_subst, binds) }
613 Note [Lookup in-scope]
614 ~~~~~~~~~~~~~~~~~~~~~~
615 Consider this example
616 foo :: Int -> Maybe Int -> Int
618 foo m (Just n) = foo (m-n) (Just n)
620 SpecConstr sees this fragment:
622 case w_smT of wild_Xf [Just A] {
623 Data.Maybe.Nothing -> lvl_smf;
624 Data.Maybe.Just n_acT [Just S(L)] ->
625 case n_acT of wild1_ams [Just A] { GHC.Base.I# y_amr [Just L] ->
626 $wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf
629 and correctly generates the rule
631 RULES: "SC:$wfoo1" [0] __forall {y_amr [Just L] :: GHC.Prim.Int#
632 sc_snn :: GHC.Prim.Int#}
633 $wfoo_smW sc_snn (Data.Maybe.Just @ GHC.Base.Int (GHC.Base.I# y_amr))
634 = $s$wfoo_sno y_amr sc_snn ;]
636 BUT we must ensure that this rule matches in the original function!
637 Note that the call to $wfoo is
638 $wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf
640 During matching we expand wild_Xf to (Just n_acT). But then we must also
641 expand n_acT to (I# y_amr). And we can only do that if we look up n_acT
642 in the in-scope set, because in wild_Xf's unfolding it won't have an unfolding
645 That is why the 'lookupRnInScope' call in the (Var v2) case of 'match'
649 %************************************************************************
651 \subsection{Checking a program for failing rule applications}
653 %************************************************************************
655 -----------------------------------------------------
657 -----------------------------------------------------
659 We want to know what sites have rules that could have fired but didn't.
660 This pass runs over the tree (without changing it) and reports such.
662 NB: we assume that this follows a run of the simplifier, so every Id
663 occurrence (including occurrences of imported Ids) is decorated with
664 all its (active) rules. No need to construct a rule base or anything
668 ruleCheckProgram :: CompilerPhase -> String -> [CoreBind] -> SDoc
669 -- Report partial matches for rules beginning
670 -- with the specified string
671 ruleCheckProgram phase rule_pat binds
673 = text "Rule check results: no rule application sites"
675 = vcat [text "Rule check results:",
677 vcat [ p $$ line | p <- bagToList results ]
680 results = unionManyBags (map (ruleCheckBind (phase, rule_pat)) binds)
681 line = text (replicate 20 '-')
683 type RuleCheckEnv = (CompilerPhase, String) -- Phase and Pattern
685 ruleCheckBind :: RuleCheckEnv -> CoreBind -> Bag SDoc
686 -- The Bag returned has one SDoc for each call site found
687 ruleCheckBind env (NonRec b r) = ruleCheck env r
688 ruleCheckBind env (Rec prs) = unionManyBags [ruleCheck env r | (b,r) <- prs]
690 ruleCheck :: RuleCheckEnv -> CoreExpr -> Bag SDoc
691 ruleCheck env (Var v) = emptyBag
692 ruleCheck env (Lit l) = emptyBag
693 ruleCheck env (Type ty) = emptyBag
694 ruleCheck env (App f a) = ruleCheckApp env (App f a) []
695 ruleCheck env (Note n e) = ruleCheck env e
696 ruleCheck env (Cast e co) = ruleCheck env e
697 ruleCheck env (Let bd e) = ruleCheckBind env bd `unionBags` ruleCheck env e
698 ruleCheck env (Lam b e) = ruleCheck env e
699 ruleCheck env (Case e _ _ as) = ruleCheck env e `unionBags`
700 unionManyBags [ruleCheck env r | (_,_,r) <- as]
702 ruleCheckApp env (App f a) as = ruleCheck env a `unionBags` ruleCheckApp env f (a:as)
703 ruleCheckApp env (Var f) as = ruleCheckFun env f as
704 ruleCheckApp env other as = ruleCheck env other
708 ruleCheckFun :: RuleCheckEnv -> Id -> [CoreExpr] -> Bag SDoc
709 -- Produce a report for all rules matching the predicate
710 -- saying why it doesn't match the specified application
712 ruleCheckFun (phase, pat) fn args
713 | null name_match_rules = emptyBag
714 | otherwise = unitBag (ruleAppCheck_help phase fn args name_match_rules)
716 name_match_rules = filter match (idCoreRules fn)
717 match rule = pat `isPrefixOf` unpackFS (ruleName rule)
719 ruleAppCheck_help :: CompilerPhase -> Id -> [CoreExpr] -> [CoreRule] -> SDoc
720 ruleAppCheck_help phase fn args rules
721 = -- The rules match the pattern, so we want to print something
722 vcat [text "Expression:" <+> ppr (mkApps (Var fn) args),
723 vcat (map check_rule rules)]
726 i_args = args `zip` [1::Int ..]
727 rough_args = map roughTopName args
729 check_rule rule = rule_herald rule <> colon <+> rule_info rule
731 rule_herald (BuiltinRule { ru_name = name })
732 = ptext SLIT("Builtin rule") <+> doubleQuotes (ftext name)
733 rule_herald (Rule { ru_name = name })
734 = ptext SLIT("Rule") <+> doubleQuotes (ftext name)
737 | Just _ <- matchRule noBlackList emptyInScopeSet args rough_args rule
738 = text "matches (which is very peculiar!)"
740 rule_info (BuiltinRule {}) = text "does not match"
742 rule_info (Rule { ru_name = name, ru_act = act,
743 ru_bndrs = rule_bndrs, ru_args = rule_args})
744 | not (isActive phase act) = text "active only in later phase"
745 | n_args < n_rule_args = text "too few arguments"
746 | n_mismatches == n_rule_args = text "no arguments match"
747 | n_mismatches == 0 = text "all arguments match (considered individually), but rule as a whole does not"
748 | otherwise = text "arguments" <+> ppr mismatches <+> text "do not match (1-indexing)"
750 n_rule_args = length rule_args
751 n_mismatches = length mismatches
752 mismatches = [i | (rule_arg, (arg,i)) <- rule_args `zip` i_args,
753 not (isJust (match_fn rule_arg arg))]
755 lhs_fvs = exprsFreeVars rule_args -- Includes template tyvars
756 match_fn rule_arg arg = match menv emptySubstEnv rule_arg arg
758 in_scope = lhs_fvs `unionVarSet` exprFreeVars arg
759 menv = ME { me_env = mkRnEnv2 (mkInScopeSet in_scope)
760 , me_tmpls = mkVarSet rule_bndrs }