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