6901821c9f05d620135ac3581d13661d25223059
[ghc-hetmet.git] / ghc / compiler / specialise / Rules.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[CoreRules]{Transformation rules}
5
6 \begin{code}
7 module Rules (
8         RuleBase, emptyRuleBase, mkRuleBase, extendRuleBaseList, 
9         unionRuleBase, pprRuleBase, ruleCheckProgram,
10
11         mkSpecInfo, extendSpecInfo, addSpecInfo,
12         rulesOfBinds, addIdSpecialisations, 
13
14         lookupRule, mkLocalRule, roughTopNames
15     ) where
16
17 #include "HsVersions.h"
18
19 import CoreSyn          -- All of it
20 import OccurAnal        ( occurAnalyseGlobalExpr )
21 import CoreFVs          ( exprFreeVars, exprsFreeVars, rulesRhsFreeVars )
22 import CoreUnfold       ( isCheapUnfolding, unfoldingTemplate )
23 import CoreUtils        ( tcEqExprX )
24 import PprCore          ( pprRules )
25 import Type             ( Type )
26 import TcType           ( tcSplitTyConApp_maybe )
27 import CoreTidy         ( tidyRules )
28 import Id               ( Id, idUnfolding, isLocalId, isGlobalId, idName,
29                           idSpecialisation, idCoreRules, setIdSpecialisation ) 
30 import IdInfo           ( SpecInfo( SpecInfo ) )
31 import Var              ( Var )
32 import VarEnv           ( IdEnv, TyVarEnv, InScopeSet, emptyTidyEnv,
33                           emptyInScopeSet, mkInScopeSet, extendInScopeSetList, 
34                           emptyVarEnv, lookupVarEnv, extendVarEnv, 
35                           nukeRnEnvL, mkRnEnv2, rnOccR, rnOccL, inRnEnvR,
36                           rnBndrR, rnBndr2, rnBndrL, rnBndrs2 )
37 import VarSet
38 import Name             ( Name, NamedThing(..), nameOccName )
39 import NameEnv
40 import Unify            ( tcMatchTyX, MatchEnv(..) )
41 import BasicTypes       ( Activation, CompilerPhase, isActive )
42
43 import Outputable
44 import FastString
45 import Maybe            ( isJust )
46 import Bag
47 import List             ( isPrefixOf )
48 \end{code}
49
50
51 %************************************************************************
52 %*                                                                      *
53 \subsection[specialisation-IdInfo]{Specialisation info about an @Id@}
54 %*                                                                      *
55 %************************************************************************
56
57 A @CoreRule@ holds details of one rule for an @Id@, which
58 includes its specialisations.
59
60 For example, if a rule for @f@ contains the mapping:
61 \begin{verbatim}
62         forall a b d. [Type (List a), Type b, Var d]  ===>  f' a b
63 \end{verbatim}
64 then when we find an application of f to matching types, we simply replace
65 it by the matching RHS:
66 \begin{verbatim}
67         f (List Int) Bool dict ===>  f' Int Bool
68 \end{verbatim}
69 All the stuff about how many dictionaries to discard, and what types
70 to apply the specialised function to, are handled by the fact that the
71 Rule contains a template for the result of the specialisation.
72
73 There is one more exciting case, which is dealt with in exactly the same
74 way.  If the specialised value is unboxed then it is lifted at its
75 definition site and unlifted at its uses.  For example:
76
77         pi :: forall a. Num a => a
78
79 might have a specialisation
80
81         [Int#] ===>  (case pi' of Lift pi# -> pi#)
82
83 where pi' :: Lift Int# is the specialised version of pi.
84
85 \begin{code}
86 mkLocalRule :: RuleName -> Activation 
87             -> Name -> [CoreBndr] -> [CoreExpr] -> CoreExpr -> CoreRule
88 -- Used to make CoreRule for an Id defined in this module
89 mkLocalRule name act fn bndrs args rhs
90   = Rule { ru_name = name, ru_fn = fn, ru_act = act,
91            ru_bndrs = bndrs, ru_args = args,
92            ru_rhs = rhs, ru_rough = roughTopNames args,
93            ru_orph = Just (nameOccName fn), ru_local = True }
94
95 --------------
96 roughTopNames :: [CoreExpr] -> [Maybe Name]
97 roughTopNames args = map roughTopName args
98
99 roughTopName :: CoreExpr -> Maybe Name
100 -- Find the "top" free name of an expression
101 -- a) the function in an App chain (if a GlobalId)
102 -- b) the TyCon in a type
103 -- This is used for the fast-match-check for rules; 
104 --      if the top names don't match, the rest can't
105 roughTopName (Type ty) = case tcSplitTyConApp_maybe ty of
106                           Just (tc,_) -> Just (getName tc)
107                           Nothing     -> Nothing
108 roughTopName (App f a) = roughTopName f
109 roughTopName (Var f) | isGlobalId f = Just (idName f)
110                      | otherwise    = Nothing
111 roughTopName other = Nothing
112
113 ruleCantMatch :: [Maybe Name] -> [Maybe Name] -> Bool
114 -- (ruleCantMatch tpl actual) returns True only if 'actual'
115 -- definitely can't match 'tpl' by instantiating 'tpl'.  
116 -- It's only a one-way match; unlike instance matching we 
117 -- don't consider unification
118 ruleCantMatch (Just n1 : ts) (Just n2 : as) = n1 /= n2 || ruleCantMatch ts as
119 ruleCantMatch (Just n1 : ts) (Nothing : as) = True
120 ruleCantMatch (t       : ts) (a       : as) = ruleCantMatch ts as
121 ruleCantMatch ts             as             = False
122 \end{code}
123
124
125 %************************************************************************
126 %*                                                                      *
127                 SpecInfo: the rules in an IdInfo
128 %*                                                                      *
129 %************************************************************************
130
131 \begin{code}
132 mkSpecInfo :: [CoreRule] -> SpecInfo
133 mkSpecInfo rules = SpecInfo rules (rulesRhsFreeVars rules)
134
135 extendSpecInfo :: SpecInfo -> [CoreRule] -> SpecInfo
136 extendSpecInfo (SpecInfo rs1 fvs1) rs2
137   = SpecInfo (rs2 ++ rs1) (rulesRhsFreeVars rs2 `unionVarSet` fvs1)
138
139 addSpecInfo :: SpecInfo -> SpecInfo -> SpecInfo
140 addSpecInfo (SpecInfo rs1 fvs1) (SpecInfo rs2 fvs2) 
141   = SpecInfo (rs1 ++ rs2) (fvs1 `unionVarSet` fvs2)
142
143 addIdSpecialisations :: Id -> [CoreRule] -> Id
144 addIdSpecialisations id rules
145   = setIdSpecialisation id $
146     extendSpecInfo (idSpecialisation id) rules
147
148 rulesOfBinds :: [CoreBind] -> [CoreRule]
149 rulesOfBinds binds = concatMap (concatMap idCoreRules . bindersOf) binds
150 \end{code}
151
152
153 %************************************************************************
154 %*                                                                      *
155                 RuleBase
156 %*                                                                      *
157 %************************************************************************
158
159 \begin{code}
160 type RuleBase = NameEnv [CoreRule]
161         -- Maps (the name of) an Id to its rules
162         -- The rules are are unordered; 
163         -- we sort out any overlaps on lookup
164
165 emptyRuleBase = emptyNameEnv
166
167 mkRuleBase :: [CoreRule] -> RuleBase
168 mkRuleBase rules = extendRuleBaseList emptyRuleBase rules
169
170 extendRuleBaseList :: RuleBase -> [CoreRule] -> RuleBase
171 extendRuleBaseList rule_base new_guys
172   = foldl extendRuleBase rule_base new_guys
173
174 unionRuleBase :: RuleBase -> RuleBase -> RuleBase
175 unionRuleBase rb1 rb2 = plusNameEnv_C (++) rb1 rb2
176
177 extendRuleBase :: RuleBase -> CoreRule -> RuleBase
178 extendRuleBase rule_base rule
179   = extendNameEnv_C add rule_base (ruleIdName rule) [rule]
180   where
181     add rules _ = rule : rules
182
183 pprRuleBase :: RuleBase -> SDoc
184 pprRuleBase rules = vcat [ pprRules (tidyRules emptyTidyEnv rs) 
185                          | rs <- nameEnvElts rules ]
186 \end{code}
187
188
189 %************************************************************************
190 %*                                                                      *
191 \subsection{Matching}
192 %*                                                                      *
193 %************************************************************************
194
195 \begin{code}
196 lookupRule :: (Activation -> Bool) -> InScopeSet
197            -> RuleBase  -- Imported rules
198            -> Id -> [CoreExpr] -> Maybe (RuleName, CoreExpr)
199 lookupRule is_active in_scope rule_base fn args
200   = matchRules is_active in_scope fn args rules
201   where
202     rules | isLocalId fn = idCoreRules fn
203           | otherwise    = case lookupNameEnv rule_base (idName fn) of
204                                 Just rules -> rules
205                                 Nothing    -> []
206
207 matchRules :: (Activation -> Bool) -> InScopeSet
208            -> Id -> [CoreExpr]
209            -> [CoreRule] -> Maybe (RuleName, CoreExpr)
210 -- See comments on matchRule
211 matchRules is_active in_scope fn args rules
212   = case go [] rules of
213         []     -> Nothing
214         (m:ms) -> Just (case findBest (fn,args) m ms of
215                           (rule, ans) -> (ru_name rule, ans))
216   where
217     rough_args = map roughTopName args
218
219     go :: [(CoreRule,CoreExpr)] -> [CoreRule] -> [(CoreRule,CoreExpr)]
220     go ms []           = ms
221     go ms (r:rs) = case (matchRule is_active in_scope args rough_args r) of
222                         Just e  -> go ((r,e):ms) rs
223                         Nothing -> go ms         rs
224
225 findBest :: (Id, [CoreExpr])
226          -> (CoreRule,CoreExpr) -> [(CoreRule,CoreExpr)] -> (CoreRule,CoreExpr)
227 -- All these pairs matched the expression
228 -- Return the pair the the most specific rule
229 -- The (fn,args) is just for overlap reporting
230
231 findBest target (rule,ans)   [] = (rule,ans)
232 findBest target (rule1,ans1) ((rule2,ans2):prs)
233   | rule1 `isMoreSpecific` rule2 = findBest target (rule1,ans1) prs
234   | rule2 `isMoreSpecific` rule1 = findBest target (rule1,ans1) prs
235   | otherwise = pprTrace "Rules.findBest: rule overlap (Rule 1 wins)"
236                          (vcat [ptext SLIT("Expression to match:") <+> ppr fn <+> sep (map ppr args),
237                                 ptext SLIT("Rule 1:") <+> ppr rule1, 
238                                 ptext SLIT("Rule 2:") <+> ppr rule2]) $
239                 findBest target (rule1,ans1) prs
240   where
241     (fn,args) = target
242
243 isMoreSpecific :: CoreRule -> CoreRule -> Bool
244 isMoreSpecific (BuiltinRule {}) r2 = True
245 isMoreSpecific r1 (BuiltinRule {}) = False
246 isMoreSpecific (Rule { ru_bndrs = bndrs1, ru_args = args1 })
247                (Rule { ru_bndrs = bndrs2, ru_args = args2 })
248   = isJust (matchN in_scope bndrs2 args2 args1)
249   where
250    in_scope = mkInScopeSet (mkVarSet bndrs1)
251         -- Actually we should probably include the free vars 
252         -- of rule1's args, but I can't be bothered
253
254 noBlackList :: Activation -> Bool
255 noBlackList act = False         -- Nothing is black listed
256
257 matchRule :: (Activation -> Bool) -> InScopeSet
258           -> [CoreExpr] -> [Maybe Name]
259           -> CoreRule -> Maybe CoreExpr
260
261 -- If (matchRule rule args) returns Just (name,rhs)
262 -- then (f args) matches the rule, and the corresponding
263 -- rewritten RHS is rhs
264 --
265 -- The bndrs and rhs is occurrence-analysed
266 --
267 --      Example
268 --
269 -- The rule
270 --      forall f g x. map f (map g x) ==> map (f . g) x
271 -- is stored
272 --      CoreRule "map/map" 
273 --               [f,g,x]                -- tpl_vars
274 --               [f,map g x]            -- tpl_args
275 --               map (f.g) x)           -- rhs
276 --        
277 -- Then the call: matchRule the_rule [e1,map e2 e3]
278 --        = Just ("map/map", (\f,g,x -> rhs) e1 e2 e3)
279 --
280 -- Any 'surplus' arguments in the input are simply put on the end
281 -- of the output.
282
283 matchRule is_active in_scope args rough_args
284           (BuiltinRule { ru_name = name, ru_try = match_fn })
285   = case match_fn args of
286         Just expr -> Just expr
287         Nothing   -> Nothing
288
289 matchRule is_active in_scope args rough_args
290           (Rule { ru_name = rn, ru_act = act, ru_rough = tpl_tops,
291                   ru_bndrs = tpl_vars, ru_args = tpl_args,
292                   ru_rhs = rhs })
293   | not (is_active act)               = Nothing
294   | ruleCantMatch tpl_tops rough_args = Nothing
295   | otherwise
296   = case matchN in_scope tpl_vars tpl_args args of
297         Nothing                    -> Nothing
298         Just (tpl_vals, leftovers) -> Just (rule_fn
299                                             `mkApps` tpl_vals
300                                             `mkApps` leftovers)
301   where
302     rule_fn = occurAnalyseGlobalExpr (mkLams tpl_vars rhs)
303         -- We could do this when putting things into the rulebase, I guess
304 \end{code}
305
306 \begin{code}
307 matchN  :: InScopeSet
308         -> [Var]                -- Template tyvars
309         -> [CoreExpr]           -- Template
310         -> [CoreExpr]           -- Target; can have more elts than template
311         -> Maybe ([CoreExpr],   -- What is substituted for each template var
312                   [CoreExpr])   -- Leftover target exprs
313
314 matchN in_scope tmpl_vars tmpl_es target_es
315   = do  { (subst, leftover_es) <- go init_menv emptySubstEnv tmpl_es target_es
316         ; return (map (lookup_tmpl subst) tmpl_vars, leftover_es) }
317   where
318     init_menv = ME { me_tmpls = mkVarSet tmpl_vars, me_env = init_rn_env }
319     init_rn_env = mkRnEnv2 (extendInScopeSetList in_scope tmpl_vars)
320                 
321     go menv subst []     es     = Just (subst, es)
322     go menv subst ts     []     = Nothing       -- Fail if too few actual args
323     go menv subst (t:ts) (e:es) = do { subst1 <- match menv subst t e 
324                                      ; go menv subst1 ts es }
325
326     lookup_tmpl :: (TvSubstEnv, IdSubstEnv) -> Var -> CoreExpr
327     lookup_tmpl (tv_subst, id_subst) tmpl_var
328         | isTyVar tmpl_var = case lookupVarEnv tv_subst tmpl_var of
329                                 Just ty         -> Type ty
330                                 Nothing         -> unbound tmpl_var
331         | otherwise        = case lookupVarEnv id_subst tmpl_var of
332                                 Just e -> e
333                                 other  -> unbound tmpl_var
334  
335     unbound var = pprPanic "Template variable unbound in rewrite rule" (ppr var)
336 \end{code}
337
338
339         ---------------------------------------------
340                 The inner workings of matching
341         ---------------------------------------------
342
343 \begin{code}
344 -- These two definitions are not the same as in Subst,
345 -- but they simple and direct, and purely local to this module
346 -- The third, for TvSubstEnv, is the same as in VarEnv, but repeated here
347 -- for uniformity with IdSubstEnv
348 type SubstEnv   = (TvSubstEnv, IdSubstEnv)      
349 type IdSubstEnv = IdEnv    CoreExpr             
350 type TvSubstEnv = TyVarEnv Type
351
352 emptySubstEnv :: SubstEnv
353 emptySubstEnv = (emptyVarEnv, emptyVarEnv)
354
355
356 --      At one stage I tried to match even if there are more 
357 --      template args than real args.
358
359 --      I now think this is probably a bad idea.
360 --      Should the template (map f xs) match (map g)?  I think not.
361 --      For a start, in general eta expansion wastes work.
362 --      SLPJ July 99
363
364
365 match :: MatchEnv
366       -> SubstEnv
367       -> CoreExpr               -- Template
368       -> CoreExpr               -- Target
369       -> Maybe SubstEnv
370
371 -- See the notes with Unify.match, which matches types
372 -- Everything is very similar for terms
373
374 -- Interesting examples:
375 -- Consider matching
376 --      \x->f      against    \f->f
377 -- When we meet the lambdas we must remember to rename f to f' in the
378 -- second expresion.  The RnEnv2 does that.
379 --
380 -- Consider matching 
381 --      forall a. \b->b    against   \a->3
382 -- We must rename the \a.  Otherwise when we meet the lambdas we 
383 -- might substitute [a/b] in the template, and then erroneously 
384 -- succeed in matching what looks like the template variable 'a' against 3.
385
386 -- The Var case follows closely what happens in Unify.match
387 match menv subst@(tv_subst, id_subst) (Var v1) e2 
388   | v1 `elemVarSet` me_tmpls menv
389   = case lookupVarEnv id_subst v1' of
390         Nothing | any (inRnEnvR rn_env) (varSetElems (exprFreeVars e2))
391                 -> Nothing      -- Occurs check failure
392                 -- e.g. match forall a. (\x-> a x) against (\y. y y)
393
394                 | otherwise
395                 -> Just (tv_subst, extendVarEnv id_subst v1 e2)
396
397         Just e2' | tcEqExprX (nukeRnEnvL rn_env) e2' e2 
398                  -> Just subst
399
400         other -> Nothing
401
402   | otherwise   -- v1 is not a template variable
403   = case e2 of
404         Var v2 | v1' == rnOccR rn_env v2 -> Just subst
405         other                            -> Nothing
406   where
407     rn_env = me_env menv
408     v1'    = rnOccL rn_env v1
409
410 -- Here is another important rule: if the term being matched is a
411 -- variable, we expand it so long as its unfolding is a WHNF
412 -- (Its occurrence information is not necessarily up to date,
413 --  so we don't use it.)
414 match menv subst e1 (Var v2)
415   | isCheapUnfolding unfolding
416   = match menv subst e1 (unfoldingTemplate unfolding)
417   where
418     unfolding = idUnfolding v2
419
420 match menv subst (Lit lit1) (Lit lit2)
421   | lit1 == lit2
422   = Just subst
423
424 match menv subst (App f1 a1) (App f2 a2)
425   = do  { subst' <- match menv subst f1 f2
426         ; match menv subst' a1 a2 }
427
428 match menv subst (Lam x1 e1) (Lam x2 e2)
429   = match menv' subst e1 e2
430   where
431     menv' = menv { me_env = rnBndr2 (me_env menv) x1 x2 }
432
433 -- This rule does eta expansion
434 --              (\x.M)  ~  N    iff     M  ~  N x
435 match menv subst (Lam x1 e1) e2
436   = match menv' subst e1 (App e2 (varToCoreExpr new_x))
437   where
438     (rn_env', new_x) = rnBndrL (me_env menv) x1
439     menv' = menv { me_env = rn_env' }
440
441 -- Eta expansion the other way
442 --      M  ~  (\y.N)    iff   M y     ~  N
443 match menv subst e1 (Lam x2 e2)
444   = match menv' subst (App e1 (varToCoreExpr new_x)) e2
445   where
446     (rn_env', new_x) = rnBndrR (me_env menv) x2
447     menv' = menv { me_env = rn_env' }
448
449 match menv subst (Case e1 x1 ty1 alts1) (Case e2 x2 ty2 alts2)
450   = do  { subst1 <- match_ty menv subst ty1 ty2
451         ; subst2 <- match menv subst1 e1 e2
452         ; let menv' = menv { me_env = rnBndr2 (me_env menv) x2 x2 }
453         ; match_alts menv' subst2 alts1 alts2   -- Alts are both sorted
454         }
455
456 match menv subst (Type ty1) (Type ty2)
457   = match_ty menv subst ty1 ty2
458
459 match menv subst (Note (Coerce to1 from1) e1) (Note (Coerce to2 from2) e2)
460   = do  { subst1 <- match_ty menv subst  to1   to2
461         ; subst2 <- match_ty menv subst1 from1 from2
462         ; match menv subst2 e1 e2 }
463
464 -- This is an interesting rule: we simply ignore lets in the 
465 -- term being matched against!  The unfolding inside it is (by assumption)
466 -- already inside any occurrences of the bound variables, so we'll expand
467 -- them when we encounter them.
468 match menv subst e1 (Let (NonRec x2 r2) e2)
469   = match menv' subst e1 e2
470   where
471     menv' = menv { me_env = fst (rnBndrR (me_env menv) x2) }
472         -- It's important to do this renaming. For example:
473         -- Matching
474         --      forall f,x,xs. f (x:xs)
475         --   against
476         --      f (let y = e in (y:[]))
477         -- We must not get success with x->y!  Instead, we 
478         -- need an occurs check.
479
480 -- Everything else fails
481 match menv subst e1 e2 = Nothing
482
483 ------------------------------------------
484 match_alts :: MatchEnv
485       -> SubstEnv
486       -> [CoreAlt]              -- Template
487       -> [CoreAlt]              -- Target
488       -> Maybe SubstEnv
489 match_alts menv subst [] []
490   = return subst
491 match_alts menv subst ((c1,vs1,r1):alts1) ((c2,vs2,r2):alts2)
492   | c1 == c2
493   = do  { subst1 <- match menv' subst r1 r2
494         ; match_alts menv subst1 alts1 alts2 }
495   where
496     menv' :: MatchEnv
497     menv' = menv { me_env = rnBndrs2 (me_env menv) vs1 vs2 }
498
499 match_alts menv subst alts1 alts2 
500   = Nothing
501 \end{code}
502
503 Matching Core types: use the matcher in TcType.
504 Notice that we treat newtypes as opaque.  For example, suppose 
505 we have a specialised version of a function at a newtype, say 
506         newtype T = MkT Int
507 We only want to replace (f T) with f', not (f Int).
508
509 \begin{code}
510 ------------------------------------------
511 match_ty menv (tv_subst, id_subst) ty1 ty2
512   = do  { tv_subst' <- Unify.tcMatchTyX menv tv_subst ty1 ty2
513         ; return (tv_subst', id_subst) }
514 \end{code}
515
516
517 %************************************************************************
518 %*                                                                      *
519 \subsection{Checking a program for failing rule applications}
520 %*                                                                      *
521 %************************************************************************
522
523 -----------------------------------------------------
524                         Game plan
525 -----------------------------------------------------
526
527 We want to know what sites have rules that could have fired but didn't.
528 This pass runs over the tree (without changing it) and reports such.
529
530 NB: we assume that this follows a run of the simplifier, so every Id
531 occurrence (including occurrences of imported Ids) is decorated with
532 all its (active) rules.  No need to construct a rule base or anything
533 like that.
534
535 \begin{code}
536 ruleCheckProgram :: CompilerPhase -> String -> [CoreBind] -> SDoc
537 -- Report partial matches for rules beginning 
538 -- with the specified string
539 ruleCheckProgram phase rule_pat binds 
540   | isEmptyBag results
541   = text "Rule check results: no rule application sites"
542   | otherwise
543   = vcat [text "Rule check results:",
544           line,
545           vcat [ p $$ line | p <- bagToList results ]
546          ]
547   where
548     results = unionManyBags (map (ruleCheckBind (phase, rule_pat)) binds)
549     line = text (replicate 20 '-')
550           
551 type RuleCheckEnv = (CompilerPhase, String)     -- Phase and Pattern
552
553 ruleCheckBind :: RuleCheckEnv -> CoreBind -> Bag SDoc
554    -- The Bag returned has one SDoc for each call site found
555 ruleCheckBind env (NonRec b r) = ruleCheck env r
556 ruleCheckBind env (Rec prs)    = unionManyBags [ruleCheck env r | (b,r) <- prs]
557
558 ruleCheck :: RuleCheckEnv -> CoreExpr -> Bag SDoc
559 ruleCheck env (Var v)       = emptyBag
560 ruleCheck env (Lit l)       = emptyBag
561 ruleCheck env (Type ty)     = emptyBag
562 ruleCheck env (App f a)     = ruleCheckApp env (App f a) []
563 ruleCheck env (Note n e)    = ruleCheck env e
564 ruleCheck env (Let bd e)    = ruleCheckBind env bd `unionBags` ruleCheck env e
565 ruleCheck env (Lam b e)     = ruleCheck env e
566 ruleCheck env (Case e _ _ as) = ruleCheck env e `unionBags` 
567                                 unionManyBags [ruleCheck env r | (_,_,r) <- as]
568
569 ruleCheckApp env (App f a) as = ruleCheck env a `unionBags` ruleCheckApp env f (a:as)
570 ruleCheckApp env (Var f) as   = ruleCheckFun env f as
571 ruleCheckApp env other as     = ruleCheck env other
572 \end{code}
573
574 \begin{code}
575 ruleCheckFun :: RuleCheckEnv -> Id -> [CoreExpr] -> Bag SDoc
576 -- Produce a report for all rules matching the predicate
577 -- saying why it doesn't match the specified application
578
579 ruleCheckFun (phase, pat) fn args
580   | null name_match_rules = emptyBag
581   | otherwise             = unitBag (ruleAppCheck_help phase fn args name_match_rules)
582   where
583     name_match_rules = filter match (idCoreRules fn)
584     match rule = pat `isPrefixOf` unpackFS (ruleName rule)
585
586 ruleAppCheck_help :: CompilerPhase -> Id -> [CoreExpr] -> [CoreRule] -> SDoc
587 ruleAppCheck_help phase fn args rules
588   =     -- The rules match the pattern, so we want to print something
589     vcat [text "Expression:" <+> ppr (mkApps (Var fn) args),
590           vcat (map check_rule rules)]
591   where
592     n_args = length args
593     i_args = args `zip` [1::Int ..]
594     rough_args = map roughTopName args
595
596     check_rule rule = rule_herald rule <> colon <+> rule_info rule
597
598     rule_herald (BuiltinRule { ru_name = name })
599         = ptext SLIT("Builtin rule") <+> doubleQuotes (ftext name)
600     rule_herald (Rule { ru_name = name })
601         = ptext SLIT("Rule") <+> doubleQuotes (ftext name)
602
603     rule_info rule
604         | Just _ <- matchRule noBlackList emptyInScopeSet args rough_args rule
605         = text "matches (which is very peculiar!)"
606
607     rule_info (BuiltinRule {}) = text "does not match"
608
609     rule_info (Rule { ru_name = name, ru_act = act, 
610                       ru_bndrs = rule_bndrs, ru_args = rule_args})
611         | not (isActive phase act)    = text "active only in later phase"
612         | n_args < n_rule_args        = text "too few arguments"
613         | n_mismatches == n_rule_args = text "no arguments match"
614         | n_mismatches == 0           = text "all arguments match (considered individually), but rule as a whole does not"
615         | otherwise                   = text "arguments" <+> ppr mismatches <+> text "do not match (1-indexing)"
616         where
617           n_rule_args  = length rule_args
618           n_mismatches = length mismatches
619           mismatches   = [i | (rule_arg, (arg,i)) <- rule_args `zip` i_args,
620                               not (isJust (match_fn rule_arg arg))]
621
622           lhs_fvs = exprsFreeVars rule_args     -- Includes template tyvars
623           match_fn rule_arg arg = match menv emptySubstEnv rule_arg arg
624                 where
625                   in_scope = lhs_fvs `unionVarSet` exprFreeVars arg
626                   menv = ME { me_env   = mkRnEnv2 (mkInScopeSet in_scope)
627                             , me_tmpls = mkVarSet rule_bndrs }
628 \end{code}
629