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