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