Fix warnings in Rules
[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 -- | Functions for collecting together and applying rewrite rules to a module.
8 -- The 'CoreRule' datatype itself is declared elsewhere.
9 module Rules (
10         -- * RuleBase
11         RuleBase, 
12         
13         -- ** Constructing 
14         emptyRuleBase, mkRuleBase, extendRuleBaseList, 
15         unionRuleBase, pprRuleBase, 
16         
17         -- ** Checking rule applications
18         ruleCheckProgram,
19
20         -- ** Manipulating 'SpecInfo' rules
21         mkSpecInfo, extendSpecInfo, addSpecInfo,
22         addIdSpecialisations, 
23         
24         -- * Misc. CoreRule helpers
25         rulesOfBinds, getRules, pprRulesForUser,
26         
27         lookupRule, mkLocalRule, roughTopNames
28     ) where
29
30 #include "HsVersions.h"
31
32 import CoreSyn          -- All of it
33 import OccurAnal        ( occurAnalyseExpr )
34 import CoreFVs          ( exprFreeVars, exprsFreeVars, bindFreeVars, rulesFreeVars )
35 import CoreUtils        ( tcEqExprX, exprType )
36 import PprCore          ( pprRules )
37 import Type             ( Type, TvSubstEnv )
38 import TcType           ( tcSplitTyConApp_maybe )
39 import CoreTidy         ( tidyRules )
40 import Id
41 import IdInfo           ( SpecInfo( SpecInfo ) )
42 import Var              ( Var )
43 import VarEnv
44 import VarSet
45 import Name             ( Name, NamedThing(..) )
46 import NameEnv
47 import Unify            ( ruleMatchTyX, MatchEnv(..) )
48 import BasicTypes       ( Activation )
49 import StaticFlags      ( opt_PprStyle_Debug )
50 import Outputable
51 import FastString
52 import Maybes
53 import OrdList
54 import Bag
55 import Util
56 import Data.List
57 \end{code}
58
59
60 %************************************************************************
61 %*                                                                      *
62 \subsection[specialisation-IdInfo]{Specialisation info about an @Id@}
63 %*                                                                      *
64 %************************************************************************
65
66 A @CoreRule@ holds details of one rule for an @Id@, which
67 includes its specialisations.
68
69 For example, if a rule for @f@ contains the mapping:
70 \begin{verbatim}
71         forall a b d. [Type (List a), Type b, Var d]  ===>  f' a b
72 \end{verbatim}
73 then when we find an application of f to matching types, we simply replace
74 it by the matching RHS:
75 \begin{verbatim}
76         f (List Int) Bool dict ===>  f' Int Bool
77 \end{verbatim}
78 All the stuff about how many dictionaries to discard, and what types
79 to apply the specialised function to, are handled by the fact that the
80 Rule contains a template for the result of the specialisation.
81
82 There is one more exciting case, which is dealt with in exactly the same
83 way.  If the specialised value is unboxed then it is lifted at its
84 definition site and unlifted at its uses.  For example:
85
86         pi :: forall a. Num a => a
87
88 might have a specialisation
89
90         [Int#] ===>  (case pi' of Lift pi# -> pi#)
91
92 where pi' :: Lift Int# is the specialised version of pi.
93
94 \begin{code}
95 mkLocalRule :: RuleName -> Activation 
96             -> Name -> [CoreBndr] -> [CoreExpr] -> CoreExpr -> CoreRule
97 -- ^ Used to make 'CoreRule' for an 'Id' defined in the module being 
98 -- compiled. See also 'CoreSyn.CoreRule'
99 mkLocalRule name act fn bndrs args rhs
100   = Rule { ru_name = name, ru_fn = fn, ru_act = act,
101            ru_bndrs = bndrs, ru_args = args,
102            ru_rhs = rhs, ru_rough = roughTopNames args,
103            ru_local = True }
104
105 --------------
106 roughTopNames :: [CoreExpr] -> [Maybe Name]
107 -- ^ Find the \"top\" free names of several expressions. 
108 -- Such names are either:
109 --
110 -- 1. The function finally being applied to in an application chain
111 --    (if that name is a GlobalId: see "Var#globalvslocal"), or
112 --
113 -- 2. The 'TyCon' if the expression is a 'Type'
114 --
115 -- This is used for the fast-match-check for rules; 
116 --      if the top names don't match, the rest can't
117 roughTopNames args = map roughTopName args
118
119 roughTopName :: CoreExpr -> Maybe Name
120 roughTopName (Type ty) = case tcSplitTyConApp_maybe ty of
121                           Just (tc,_) -> Just (getName tc)
122                           Nothing     -> Nothing
123 roughTopName (App f _) = roughTopName f
124 roughTopName (Var f) | isGlobalId f = Just (idName f)
125                      | otherwise    = Nothing
126 roughTopName _ = Nothing
127
128 ruleCantMatch :: [Maybe Name] -> [Maybe Name] -> Bool
129 -- ^ @ruleCantMatch tpl actual@ returns True only if @actual@
130 -- definitely can't match @tpl@ by instantiating @tpl@.  
131 -- It's only a one-way match; unlike instance matching we 
132 -- don't consider unification.
133 -- 
134 -- Notice that [_$_]
135 --      @ruleCantMatch [Nothing] [Just n2] = False@
136 --      Reason: a template variable can be instantiated by a constant
137 -- Also:
138 --      @ruleCantMatch [Just n1] [Nothing] = False@
139 --      Reason: a local variable @v@ in the actuals might [_$_]
140
141 ruleCantMatch (Just n1 : ts) (Just n2 : as) = n1 /= n2 || ruleCantMatch ts as
142 ruleCantMatch (_       : ts) (_       : as) = ruleCantMatch ts as
143 ruleCantMatch _              _              = False
144 \end{code}
145
146 \begin{code}
147 pprRulesForUser :: [CoreRule] -> SDoc
148 -- (a) tidy the rules
149 -- (b) sort them into order based on the rule name
150 -- (c) suppress uniques (unless -dppr-debug is on)
151 -- This combination makes the output stable so we can use in testing
152 -- It's here rather than in PprCore because it calls tidyRules
153 pprRulesForUser rules
154   = withPprStyle defaultUserStyle $
155     pprRules $
156     sortLe le_rule  $
157     tidyRules emptyTidyEnv rules
158   where 
159     le_rule r1 r2 = ru_name r1 <= ru_name r2
160 \end{code}
161
162
163 %************************************************************************
164 %*                                                                      *
165                 SpecInfo: the rules in an IdInfo
166 %*                                                                      *
167 %************************************************************************
168
169 \begin{code}
170 -- | Make a 'SpecInfo' containing a number of 'CoreRule's, suitable
171 -- for putting into an 'IdInfo'
172 mkSpecInfo :: [CoreRule] -> SpecInfo
173 mkSpecInfo rules = SpecInfo rules (rulesFreeVars rules)
174
175 extendSpecInfo :: SpecInfo -> [CoreRule] -> SpecInfo
176 extendSpecInfo (SpecInfo rs1 fvs1) rs2
177   = SpecInfo (rs2 ++ rs1) (rulesFreeVars rs2 `unionVarSet` fvs1)
178
179 addSpecInfo :: SpecInfo -> SpecInfo -> SpecInfo
180 addSpecInfo (SpecInfo rs1 fvs1) (SpecInfo rs2 fvs2) 
181   = SpecInfo (rs1 ++ rs2) (fvs1 `unionVarSet` fvs2)
182
183 addIdSpecialisations :: Id -> [CoreRule] -> Id
184 addIdSpecialisations id []
185   = id
186 addIdSpecialisations id rules
187   = setIdSpecialisation id $
188     extendSpecInfo (idSpecialisation id) rules
189
190 -- | Gather all the rules for locally bound identifiers from the supplied bindings
191 rulesOfBinds :: [CoreBind] -> [CoreRule]
192 rulesOfBinds binds = concatMap (concatMap idCoreRules . bindersOf) binds
193
194 getRules :: RuleBase -> Id -> [CoreRule]
195         -- The rules for an Id come from two places:
196         --      (a) the ones it is born with (idCoreRules fn)
197         --      (b) rules added in subsequent modules (extra_rules)
198         -- PrimOps, for example, are born with a bunch of rules under (a)
199 getRules rule_base fn
200   | isLocalId fn  = idCoreRules fn
201   | otherwise     = WARN( not (isPrimOpId fn) && notNull (idCoreRules fn), 
202                           ppr fn <+> ppr (idCoreRules fn) )
203                     idCoreRules fn ++ (lookupNameEnv rule_base (idName fn) `orElse` [])
204         -- Only PrimOpIds have rules inside themselves, and perhaps more besides
205 \end{code}
206
207
208 %************************************************************************
209 %*                                                                      *
210                 RuleBase
211 %*                                                                      *
212 %************************************************************************
213
214 \begin{code}
215 -- | Gathers a collection of 'CoreRule's. Maps (the name of) an 'Id' to its rules
216 type RuleBase = NameEnv [CoreRule]
217         -- The rules are are unordered; 
218         -- we sort out any overlaps on lookup
219
220 emptyRuleBase :: RuleBase
221 emptyRuleBase = emptyNameEnv
222
223 mkRuleBase :: [CoreRule] -> RuleBase
224 mkRuleBase rules = extendRuleBaseList emptyRuleBase rules
225
226 extendRuleBaseList :: RuleBase -> [CoreRule] -> RuleBase
227 extendRuleBaseList rule_base new_guys
228   = foldl extendRuleBase rule_base new_guys
229
230 unionRuleBase :: RuleBase -> RuleBase -> RuleBase
231 unionRuleBase rb1 rb2 = plusNameEnv_C (++) rb1 rb2
232
233 extendRuleBase :: RuleBase -> CoreRule -> RuleBase
234 extendRuleBase rule_base rule
235   = extendNameEnv_Acc (:) singleton rule_base (ruleIdName rule) rule
236
237 pprRuleBase :: RuleBase -> SDoc
238 pprRuleBase rules = vcat [ pprRules (tidyRules emptyTidyEnv rs) 
239                          | rs <- nameEnvElts rules ]
240 \end{code}
241
242
243 %************************************************************************
244 %*                                                                      *
245 \subsection{Matching}
246 %*                                                                      *
247 %************************************************************************
248
249 Note [Extra args in rule matching]
250 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
251 If we find a matching rule, we return (Just (rule, rhs)), 
252 but the rule firing has only consumed as many of the input args
253 as the ruleArity says.  It's up to the caller to keep track
254 of any left-over args.  E.g. if you call
255         lookupRule ... f [e1, e2, e3]
256 and it returns Just (r, rhs), where r has ruleArity 2
257 then the real rewrite is
258         f e1 e2 e3 ==> rhs e3
259
260 You might think it'd be cleaner for lookupRule to deal with the
261 leftover arguments, by applying 'rhs' to them, but the main call
262 in the Simplifier works better as it is.  Reason: the 'args' passed
263 to lookupRule are the result of a lazy substitution
264
265 \begin{code}
266 -- | The main rule matching function. Attempts to apply all (active)
267 -- supplied rules to this instance of an application in a given
268 -- context, returning the rule applied and the resulting expression if
269 -- successful.
270 lookupRule :: (Activation -> Bool) -> InScopeSet
271             -> Id -> [CoreExpr]
272             -> [CoreRule] -> Maybe (CoreRule, CoreExpr)
273
274 -- See Note [Extra args in rule matching]
275 -- See comments on matchRule
276 lookupRule is_active in_scope fn args rules
277   = -- pprTrace "matchRules" (ppr fn <+> ppr rules) $
278     case go [] rules of
279         []     -> Nothing
280         (m:ms) -> Just (findBest (fn,args) m ms)
281   where
282     rough_args = map roughTopName args
283
284     go :: [(CoreRule,CoreExpr)] -> [CoreRule] -> [(CoreRule,CoreExpr)]
285     go ms []           = ms
286     go ms (r:rs) = case (matchRule is_active in_scope args rough_args r) of
287                         Just e  -> go ((r,e):ms) rs
288                         Nothing -> -- pprTrace "match failed" (ppr r $$ ppr args $$ 
289                                    --   ppr [(arg_id, unfoldingTemplate unf) | Var arg_id <- args, let unf = idUnfolding arg_id, isCheapUnfolding unf] )
290                                    go ms         rs
291
292 findBest :: (Id, [CoreExpr])
293          -> (CoreRule,CoreExpr) -> [(CoreRule,CoreExpr)] -> (CoreRule,CoreExpr)
294 -- All these pairs matched the expression
295 -- Return the pair the the most specific rule
296 -- The (fn,args) is just for overlap reporting
297
298 findBest _      (rule,ans)   [] = (rule,ans)
299 findBest target (rule1,ans1) ((rule2,ans2):prs)
300   | rule1 `isMoreSpecific` rule2 = findBest target (rule1,ans1) prs
301   | rule2 `isMoreSpecific` rule1 = findBest target (rule2,ans2) prs
302   | debugIsOn = let pp_rule rule
303                         | opt_PprStyle_Debug = ppr rule
304                         | otherwise          = doubleQuotes (ftext (ru_name rule))
305                 in pprTrace "Rules.findBest: rule overlap (Rule 1 wins)"
306                          (vcat [if opt_PprStyle_Debug then 
307                                    ptext (sLit "Expression to match:") <+> ppr fn <+> sep (map ppr args)
308                                 else empty,
309                                 ptext (sLit "Rule 1:") <+> pp_rule rule1, 
310                                 ptext (sLit "Rule 2:") <+> pp_rule rule2]) $
311                 findBest target (rule1,ans1) prs
312   | otherwise = findBest target (rule1,ans1) prs
313   where
314     (fn,args) = target
315
316 isMoreSpecific :: CoreRule -> CoreRule -> Bool
317 isMoreSpecific (BuiltinRule {}) _ = True
318 isMoreSpecific _ (BuiltinRule {}) = False
319 isMoreSpecific (Rule { ru_bndrs = bndrs1, ru_args = args1 })
320                (Rule { ru_bndrs = bndrs2, ru_args = args2 })
321   = isJust (matchN in_scope bndrs2 args2 args1)
322   where
323    in_scope = mkInScopeSet (mkVarSet bndrs1)
324         -- Actually we should probably include the free vars 
325         -- of rule1's args, but I can't be bothered
326
327 noBlackList :: Activation -> Bool
328 noBlackList _ = False           -- Nothing is black listed
329
330 matchRule :: (Activation -> Bool) -> InScopeSet
331           -> [CoreExpr] -> [Maybe Name]
332           -> CoreRule -> Maybe CoreExpr
333
334 -- If (matchRule rule args) returns Just (name,rhs)
335 -- then (f args) matches the rule, and the corresponding
336 -- rewritten RHS is rhs
337 --
338 -- The bndrs and rhs is occurrence-analysed
339 --
340 --      Example
341 --
342 -- The rule
343 --      forall f g x. map f (map g x) ==> map (f . g) x
344 -- is stored
345 --      CoreRule "map/map" 
346 --               [f,g,x]                -- tpl_vars
347 --               [f,map g x]            -- tpl_args
348 --               map (f.g) x)           -- rhs
349 --        
350 -- Then the call: matchRule the_rule [e1,map e2 e3]
351 --        = Just ("map/map", (\f,g,x -> rhs) e1 e2 e3)
352 --
353 -- Any 'surplus' arguments in the input are simply put on the end
354 -- of the output.
355
356 matchRule _is_active _in_scope args _rough_args
357           (BuiltinRule { ru_try = match_fn })
358   = case match_fn args of
359         Just expr -> Just expr
360         Nothing   -> Nothing
361
362 matchRule is_active in_scope args rough_args
363           (Rule { ru_act = act, ru_rough = tpl_tops,
364                   ru_bndrs = tpl_vars, ru_args = tpl_args,
365                   ru_rhs = rhs })
366   | not (is_active act)               = Nothing
367   | ruleCantMatch tpl_tops rough_args = Nothing
368   | otherwise
369   = case matchN in_scope tpl_vars tpl_args args of
370         Nothing                -> Nothing
371         Just (binds, tpl_vals) -> Just (mkLets binds $
372                                         rule_fn `mkApps` tpl_vals)
373   where
374     rule_fn = occurAnalyseExpr (mkLams tpl_vars rhs)
375         -- We could do this when putting things into the rulebase, I guess
376 \end{code}
377
378 \begin{code}
379 -- For a given match template and context, find bindings to wrap around 
380 -- the entire result and what should be substituted for each template variable.
381 -- Fail if there are two few actual arguments from the target to match the template
382 matchN  :: InScopeSet           -- ^ In-scope variables
383         -> [Var]                -- ^ Match template type variables
384         -> [CoreExpr]           -- ^ Match template
385         -> [CoreExpr]           -- ^ Target; can have more elements than the template
386         -> Maybe ([CoreBind],
387                   [CoreExpr])
388
389 matchN in_scope tmpl_vars tmpl_es target_es
390   = do  { (tv_subst, id_subst, binds)
391                 <- go init_menv emptySubstEnv tmpl_es target_es
392         ; return (fromOL binds, 
393                   map (lookup_tmpl tv_subst id_subst) tmpl_vars') }
394   where
395     (init_rn_env, tmpl_vars') = mapAccumL rnBndrL (mkRnEnv2 in_scope) tmpl_vars
396         -- See Note [Template binders]
397
398     init_menv = ME { me_tmpls = mkVarSet tmpl_vars', me_env = init_rn_env }
399                 
400     go _    subst []     _      = Just subst
401     go _    _     _      []     = Nothing       -- Fail if too few actual args
402     go menv subst (t:ts) (e:es) = do { subst1 <- match menv subst t e 
403                                      ; go menv subst1 ts es }
404
405     lookup_tmpl :: TvSubstEnv -> IdSubstEnv -> Var -> CoreExpr
406     lookup_tmpl tv_subst id_subst tmpl_var'
407         | isTyVar tmpl_var' = case lookupVarEnv tv_subst tmpl_var' of
408                                 Just ty         -> Type ty
409                                 Nothing         -> unbound tmpl_var'
410         | otherwise         = case lookupVarEnv id_subst tmpl_var' of
411                                 Just e -> e
412                                 _      -> unbound tmpl_var'
413  
414     unbound var = pprPanic "Template variable unbound in rewrite rule" 
415                         (ppr var $$ ppr tmpl_vars $$ ppr tmpl_vars' $$ ppr tmpl_es $$ ppr target_es)
416 \end{code}
417
418 Note [Template binders]
419 ~~~~~~~~~~~~~~~~~~~~~~~
420 Consider the following match:
421         Template:  forall x.  f x 
422         Target:     f (x+1)
423 This should succeed, because the template variable 'x' has 
424 nothing to do with the 'x' in the target. 
425
426 On reflection, this case probably does just work, but this might not
427         Template:  forall x. f (\x.x) 
428         Target:    f (\y.y)
429 Here we want to clone when we find the \x, but to know that x must be in scope
430
431 To achive this, we use rnBndrL to rename the template variables if
432 necessary; the renamed ones are the tmpl_vars'
433
434
435         ---------------------------------------------
436                 The inner workings of matching
437         ---------------------------------------------
438
439 \begin{code}
440 -- These two definitions are not the same as in Subst,
441 -- but they simple and direct, and purely local to this module
442 --
443 -- * The domain of the TvSubstEnv and IdSubstEnv are the template
444 --   variables passed into the match.
445 --
446 -- * The (OrdList CoreBind) in a SubstEnv are the bindings floated out
447 --   from nested matches; see the Let case of match, below
448 --
449 type SubstEnv   = (TvSubstEnv, IdSubstEnv, OrdList CoreBind)
450 type IdSubstEnv = IdEnv CoreExpr                
451
452 emptySubstEnv :: SubstEnv
453 emptySubstEnv = (emptyVarEnv, emptyVarEnv, nilOL)
454
455
456 --      At one stage I tried to match even if there are more 
457 --      template args than real args.
458
459 --      I now think this is probably a bad idea.
460 --      Should the template (map f xs) match (map g)?  I think not.
461 --      For a start, in general eta expansion wastes work.
462 --      SLPJ July 99
463
464
465 match :: MatchEnv
466       -> SubstEnv
467       -> CoreExpr               -- Template
468       -> CoreExpr               -- Target
469       -> Maybe SubstEnv
470
471 -- See the notes with Unify.match, which matches types
472 -- Everything is very similar for terms
473
474 -- Interesting examples:
475 -- Consider matching
476 --      \x->f      against    \f->f
477 -- When we meet the lambdas we must remember to rename f to f' in the
478 -- second expresion.  The RnEnv2 does that.
479 --
480 -- Consider matching 
481 --      forall a. \b->b    against   \a->3
482 -- We must rename the \a.  Otherwise when we meet the lambdas we 
483 -- might substitute [a/b] in the template, and then erroneously 
484 -- succeed in matching what looks like the template variable 'a' against 3.
485
486 -- The Var case follows closely what happens in Unify.match
487 match menv subst (Var v1) e2 
488   | Just subst <- match_var menv subst v1 e2
489   = Just subst
490
491 match menv subst e1 (Note _ e2)
492   = match menv subst e1 e2
493         -- Note [Notes in RULE matching]
494         -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
495         -- Look through Notes.  In particular, we don't want to
496         -- be confused by InlineMe notes.  Maybe we should be more
497         -- careful about profiling notes, but for now I'm just
498         -- riding roughshod over them.  
499         --- See Note [Notes in call patterns] in SpecConstr
500
501 -- Here is another important rule: if the term being matched is a
502 -- variable, we expand it so long as its unfolding is a WHNF
503 -- (Its occurrence information is not necessarily up to date,
504 --  so we don't use it.)
505 match menv subst e1 (Var v2)
506   | isCheapUnfolding unfolding
507   = match menv subst e1 (unfoldingTemplate unfolding)
508   where
509     rn_env    = me_env menv
510     unfolding = idUnfolding (lookupRnInScope rn_env (rnOccR rn_env v2))
511         -- Notice that we look up v2 in the in-scope set
512         -- See Note [Lookup in-scope]
513         -- Remember to apply any renaming first (hence rnOccR)
514
515 -- Note [Matching lets]
516 -- ~~~~~~~~~~~~~~~~~~~~
517 -- Matching a let-expression.  Consider
518 --      RULE forall x.  f (g x) = <rhs>
519 -- and target expression
520 --      f (let { w=R } in g E))
521 -- Then we'd like the rule to match, to generate
522 --      let { w=R } in (\x. <rhs>) E
523 -- In effect, we want to float the let-binding outward, to enable
524 -- the match to happen.  This is the WHOLE REASON for accumulating
525 -- bindings in the SubstEnv
526 --
527 -- We can only do this if
528 --      (a) Widening the scope of w does not capture any variables
529 --          We use a conservative test: w is not already in scope
530 --          If not, we clone the binders, and substitute
531 --      (b) The free variables of R are not bound by the part of the
532 --          target expression outside the let binding; e.g.
533 --              f (\v. let w = v+1 in g E)
534 --          Here we obviously cannot float the let-binding for w.
535 --
536 -- You may think rule (a) would never apply, because rule matching is
537 -- mostly invoked from the simplifier, when we have just run substExpr 
538 -- over the argument, so there will be no shadowing anyway.
539 -- The fly in the ointment is that the forall'd variables of the
540 -- RULE itself are considered in scope.
541 --
542 -- I though of various cheapo ways to solve this tiresome problem,
543 -- but ended up doing the straightforward thing, which is to 
544 -- clone the binders if they are in scope.  It's tiresome, and
545 -- potentially inefficient, because of the calls to substExpr,
546 -- but I don't think it'll happen much in pracice.
547
548 {-  Cases to think about
549         (let x=y+1 in \x. (x,x))
550                 --> let x=y+1 in (\x1. (x1,x1))
551         (\x. let x = y+1 in (x,x))
552                 --> let x1 = y+1 in (\x. (x1,x1)
553         (let x=y+1 in (x,x), let x=y-1 in (x,x))
554                 --> let x=y+1 in let x1=y-1 in ((x,x),(x1,x1))
555
556 Watch out!
557         (let x=y+1 in let z=x+1 in (z,z)
558                 --> matches (p,p) but watch out that the use of 
559                         x on z's rhs is OK!
560 I'm removing the cloning because that makes the above case
561 fail, because the inner let looks as if it has locally-bound vars -}
562
563 match menv (tv_subst, id_subst, binds) e1 (Let bind e2)
564   | all freshly_bound bndrs,
565     not (any locally_bound bind_fvs)
566   = match (menv { me_env = rn_env' }) 
567           (tv_subst, id_subst, binds `snocOL` bind')
568           e1 e2'
569   where
570     rn_env   = me_env menv
571     bndrs    = bindersOf  bind
572     bind_fvs = varSetElems (bindFreeVars bind)
573     locally_bound x   = inRnEnvR rn_env x
574     freshly_bound x = not (x `rnInScope` rn_env)
575     bind' = bind
576     e2'   = e2
577     rn_env' = extendRnInScopeList rn_env bndrs
578 {-
579     (rn_env', bndrs') = mapAccumL rnBndrR rn_env bndrs
580     s_prs = [(bndr, Var bndr') | (bndr,bndr') <- zip bndrs bndrs', bndr /= bndr']
581     subst = mkSubst (rnInScopeSet rn_env) emptyVarEnv (mkVarEnv s_prs)
582     (bind', e2') | null s_prs = (bind,   e2)
583                  | otherwise  = (s_bind, substExpr subst e2)
584     s_bind = case bind of
585                 NonRec {} -> NonRec (head bndrs') (head rhss)
586                 Rec {}    -> Rec (bndrs' `zip` map (substExpr subst) rhss)
587 -}
588
589 match _ subst (Lit lit1) (Lit lit2)
590   | lit1 == lit2
591   = Just subst
592
593 match menv subst (App f1 a1) (App f2 a2)
594   = do  { subst' <- match menv subst f1 f2
595         ; match menv subst' a1 a2 }
596
597 match menv subst (Lam x1 e1) (Lam x2 e2)
598   = match menv' subst e1 e2
599   where
600     menv' = menv { me_env = rnBndr2 (me_env menv) x1 x2 }
601
602 -- This rule does eta expansion
603 --              (\x.M)  ~  N    iff     M  ~  N x
604 -- It's important that this is *after* the let rule,
605 -- so that      (\x.M)  ~  (let y = e in \y.N)
606 -- does the let thing, and then gets the lam/lam rule above
607 match menv subst (Lam x1 e1) e2
608   = match menv' subst e1 (App e2 (varToCoreExpr new_x))
609   where
610     (rn_env', new_x) = rnBndrL (me_env menv) x1
611     menv' = menv { me_env = rn_env' }
612
613 -- Eta expansion the other way
614 --      M  ~  (\y.N)    iff   M y     ~  N
615 match menv subst e1 (Lam x2 e2)
616   = match menv' subst (App e1 (varToCoreExpr new_x)) e2
617   where
618     (rn_env', new_x) = rnBndrR (me_env menv) x2
619     menv' = menv { me_env = rn_env' }
620
621 match menv subst (Case e1 x1 ty1 alts1) (Case e2 x2 ty2 alts2)
622   = do  { subst1 <- match_ty menv subst ty1 ty2
623         ; subst2 <- match menv subst1 e1 e2
624         ; let menv' = menv { me_env = rnBndr2 (me_env menv) x1 x2 }
625         ; match_alts menv' subst2 alts1 alts2   -- Alts are both sorted
626         }
627
628 match menv subst (Type ty1) (Type ty2)
629   = match_ty menv subst ty1 ty2
630
631 match menv subst (Cast e1 co1) (Cast e2 co2)
632   = do  { subst1 <- match_ty menv subst co1 co2
633         ; match menv subst1 e1 e2 }
634
635 {-      REMOVING OLD CODE: I think that the above handling for let is 
636                            better than the stuff here, which looks 
637                            pretty suspicious to me.  SLPJ Sept 06
638 -- This is an interesting rule: we simply ignore lets in the 
639 -- term being matched against!  The unfolding inside it is (by assumption)
640 -- already inside any occurrences of the bound variables, so we'll expand
641 -- them when we encounter them.  This gives a chance of matching
642 --      forall x,y.  f (g (x,y))
643 -- against
644 --      f (let v = (a,b) in g v)
645
646 match menv subst e1 (Let bind e2)
647   = match (menv { me_env = rn_env' }) subst e1 e2
648   where
649     (rn_env', _bndrs') = mapAccumL rnBndrR (me_env menv) (bindersOf bind)
650         -- It's important to do this renaming, so that the bndrs
651         -- are brought into the local scope. For example:
652         -- Matching
653         --      forall f,x,xs. f (x:xs)
654         --   against
655         --      f (let y = e in (y:[]))
656         -- We must not get success with x->y!  So we record that y is
657         -- locally bound (with rnBndrR), and proceed.  The Var case
658         -- will fail when trying to bind x->y
659 -}
660
661 -- Everything else fails
662 match _ _ _e1 _e2 = -- pprTrace "Failing at" ((text "e1:" <+> ppr e1) $$ (text "e2:" <+> ppr e2)) $ 
663                          Nothing
664
665 ------------------------------------------
666 match_var :: MatchEnv
667           -> SubstEnv
668           -> Var                -- Template
669           -> CoreExpr           -- Target
670           -> Maybe SubstEnv
671 match_var menv subst@(tv_subst, id_subst, binds) v1 e2
672   | v1' `elemVarSet` me_tmpls menv
673   = case lookupVarEnv id_subst v1' of
674         Nothing | any (inRnEnvR rn_env) (varSetElems (exprFreeVars e2))
675                 -> Nothing      -- Occurs check failure
676                 -- e.g. match forall a. (\x-> a x) against (\y. y y)
677
678                 | otherwise     -- No renaming to do on e2, because no free var
679                                 -- of e2 is in the rnEnvR of the envt
680                 -- Note [Matching variable types]
681                 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
682                 -- However, we must match the *types*; e.g.
683                 --   forall (c::Char->Int) (x::Char). 
684                 --      f (c x) = "RULE FIRED"
685                 -- We must only match on args that have the right type
686                 -- It's actually quite difficult to come up with an example that shows
687                 -- you need type matching, esp since matching is left-to-right, so type
688                 -- args get matched first.  But it's possible (e.g. simplrun008) and
689                 -- this is the Right Thing to do
690                 -> do   { tv_subst' <- Unify.ruleMatchTyX menv tv_subst (idType v1') (exprType e2)
691                                                 -- c.f. match_ty below
692                         ; return (tv_subst', extendVarEnv id_subst v1' e2, binds) }
693
694         Just e1' | tcEqExprX (nukeRnEnvL rn_env) e1' e2 
695                  -> Just subst
696
697                  | otherwise
698                  -> Nothing
699
700   | otherwise   -- v1 is not a template variable; check for an exact match with e2
701   = case e2 of
702        Var v2 | v1' == rnOccR rn_env v2 -> Just subst
703        _                                -> Nothing
704
705   where
706     rn_env = me_env menv
707     v1'    = rnOccL rn_env v1   
708         -- If the template is
709         --      forall x. f x (\x -> x) = ...
710         -- Then the x inside the lambda isn't the 
711         -- template x, so we must rename first!
712                                 
713
714 ------------------------------------------
715 match_alts :: MatchEnv
716       -> SubstEnv
717       -> [CoreAlt]              -- Template
718       -> [CoreAlt]              -- Target
719       -> Maybe SubstEnv
720 match_alts _ subst [] []
721   = return subst
722 match_alts menv subst ((c1,vs1,r1):alts1) ((c2,vs2,r2):alts2)
723   | c1 == c2
724   = do  { subst1 <- match menv' subst r1 r2
725         ; match_alts menv subst1 alts1 alts2 }
726   where
727     menv' :: MatchEnv
728     menv' = menv { me_env = rnBndrs2 (me_env menv) vs1 vs2 }
729
730 match_alts _ _ _ _
731   = Nothing
732 \end{code}
733
734 Matching Core types: use the matcher in TcType.
735 Notice that we treat newtypes as opaque.  For example, suppose 
736 we have a specialised version of a function at a newtype, say 
737         newtype T = MkT Int
738 We only want to replace (f T) with f', not (f Int).
739
740 \begin{code}
741 ------------------------------------------
742 match_ty :: MatchEnv
743          -> SubstEnv
744          -> Type                -- Template
745          -> Type                -- Target
746          -> Maybe SubstEnv
747 match_ty menv (tv_subst, id_subst, binds) ty1 ty2
748   = do  { tv_subst' <- Unify.ruleMatchTyX menv tv_subst ty1 ty2
749         ; return (tv_subst', id_subst, binds) }
750 \end{code}
751
752
753 Note [Lookup in-scope]
754 ~~~~~~~~~~~~~~~~~~~~~~
755 Consider this example
756         foo :: Int -> Maybe Int -> Int
757         foo 0 (Just n) = n
758         foo m (Just n) = foo (m-n) (Just n)
759
760 SpecConstr sees this fragment:
761
762         case w_smT of wild_Xf [Just A] {
763           Data.Maybe.Nothing -> lvl_smf;
764           Data.Maybe.Just n_acT [Just S(L)] ->
765             case n_acT of wild1_ams [Just A] { GHC.Base.I# y_amr [Just L] ->
766             \$wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf
767             }};
768
769 and correctly generates the rule
770
771         RULES: "SC:$wfoo1" [0] __forall {y_amr [Just L] :: GHC.Prim.Int#
772                                           sc_snn :: GHC.Prim.Int#}
773           \$wfoo_smW sc_snn (Data.Maybe.Just @ GHC.Base.Int (GHC.Base.I# y_amr))
774           = \$s\$wfoo_sno y_amr sc_snn ;]
775
776 BUT we must ensure that this rule matches in the original function!
777 Note that the call to \$wfoo is
778             \$wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf
779
780 During matching we expand wild_Xf to (Just n_acT).  But then we must also
781 expand n_acT to (I# y_amr).  And we can only do that if we look up n_acT
782 in the in-scope set, because in wild_Xf's unfolding it won't have an unfolding
783 at all. 
784
785 That is why the 'lookupRnInScope' call in the (Var v2) case of 'match'
786 is so important.
787
788
789 %************************************************************************
790 %*                                                                      *
791 \subsection{Checking a program for failing rule applications}
792 %*                                                                      *
793 %************************************************************************
794
795 -----------------------------------------------------
796                         Game plan
797 -----------------------------------------------------
798
799 We want to know what sites have rules that could have fired but didn't.
800 This pass runs over the tree (without changing it) and reports such.
801
802 \begin{code}
803 -- | Report partial matches for rules beginning with the specified
804 -- string for the purposes of error reporting
805 ruleCheckProgram :: (Activation -> Bool)    -- ^ Rule activation test
806                  -> String                      -- ^ Rule pattern
807                  -> RuleBase                    -- ^ Database of rules
808                  -> [CoreBind]                  -- ^ Bindings to check in
809                  -> SDoc                        -- ^ Resulting check message
810 ruleCheckProgram is_active rule_pat rule_base binds 
811   | isEmptyBag results
812   = text "Rule check results: no rule application sites"
813   | otherwise
814   = vcat [text "Rule check results:",
815           line,
816           vcat [ p $$ line | p <- bagToList results ]
817          ]
818   where
819     results = unionManyBags (map (ruleCheckBind (RuleCheckEnv is_active rule_pat rule_base)) binds)
820     line = text (replicate 20 '-')
821           
822 data RuleCheckEnv = RuleCheckEnv {
823     rc_is_active :: Activation -> Bool, 
824     rc_pattern :: String, 
825     rc_rule_base :: RuleBase
826 }
827
828 ruleCheckBind :: RuleCheckEnv -> CoreBind -> Bag SDoc
829    -- The Bag returned has one SDoc for each call site found
830 ruleCheckBind env (NonRec _ r) = ruleCheck env r
831 ruleCheckBind env (Rec prs)    = unionManyBags [ruleCheck env r | (_,r) <- prs]
832
833 ruleCheck :: RuleCheckEnv -> CoreExpr -> Bag SDoc
834 ruleCheck _   (Var _)       = emptyBag
835 ruleCheck _   (Lit _)       = emptyBag
836 ruleCheck _   (Type _)      = emptyBag
837 ruleCheck env (App f a)     = ruleCheckApp env (App f a) []
838 ruleCheck env (Note _ e)    = ruleCheck env e
839 ruleCheck env (Cast e _)    = ruleCheck env e
840 ruleCheck env (Let bd e)    = ruleCheckBind env bd `unionBags` ruleCheck env e
841 ruleCheck env (Lam _ e)     = ruleCheck env e
842 ruleCheck env (Case e _ _ as) = ruleCheck env e `unionBags` 
843                                 unionManyBags [ruleCheck env r | (_,_,r) <- as]
844
845 ruleCheckApp :: RuleCheckEnv -> Expr CoreBndr -> [Arg CoreBndr] -> Bag SDoc
846 ruleCheckApp env (App f a) as = ruleCheck env a `unionBags` ruleCheckApp env f (a:as)
847 ruleCheckApp env (Var f) as   = ruleCheckFun env f as
848 ruleCheckApp env other _      = ruleCheck env other
849 \end{code}
850
851 \begin{code}
852 ruleCheckFun :: RuleCheckEnv -> Id -> [CoreExpr] -> Bag SDoc
853 -- Produce a report for all rules matching the predicate
854 -- saying why it doesn't match the specified application
855
856 ruleCheckFun env fn args
857   | null name_match_rules = emptyBag
858   | otherwise             = unitBag (ruleAppCheck_help (rc_is_active env) fn args name_match_rules)
859   where
860     name_match_rules = filter match (getRules (rc_rule_base env) fn)
861     match rule = (rc_pattern env) `isPrefixOf` unpackFS (ruleName rule)
862
863 ruleAppCheck_help :: (Activation -> Bool) -> Id -> [CoreExpr] -> [CoreRule] -> SDoc
864 ruleAppCheck_help is_active fn args rules
865   =     -- The rules match the pattern, so we want to print something
866     vcat [text "Expression:" <+> ppr (mkApps (Var fn) args),
867           vcat (map check_rule rules)]
868   where
869     n_args = length args
870     i_args = args `zip` [1::Int ..]
871     rough_args = map roughTopName args
872
873     check_rule rule = rule_herald rule <> colon <+> rule_info rule
874
875     rule_herald (BuiltinRule { ru_name = name })
876         = ptext (sLit "Builtin rule") <+> doubleQuotes (ftext name)
877     rule_herald (Rule { ru_name = name })
878         = ptext (sLit "Rule") <+> doubleQuotes (ftext name)
879
880     rule_info rule
881         | Just _ <- matchRule noBlackList emptyInScopeSet args rough_args rule
882         = text "matches (which is very peculiar!)"
883
884     rule_info (BuiltinRule {}) = text "does not match"
885
886     rule_info (Rule { ru_act = act, 
887                       ru_bndrs = rule_bndrs, ru_args = rule_args})
888         | not (is_active act)    = text "active only in later phase"
889         | n_args < n_rule_args        = text "too few arguments"
890         | n_mismatches == n_rule_args = text "no arguments match"
891         | n_mismatches == 0           = text "all arguments match (considered individually), but rule as a whole does not"
892         | otherwise                   = text "arguments" <+> ppr mismatches <+> text "do not match (1-indexing)"
893         where
894           n_rule_args  = length rule_args
895           n_mismatches = length mismatches
896           mismatches   = [i | (rule_arg, (arg,i)) <- rule_args `zip` i_args,
897                               not (isJust (match_fn rule_arg arg))]
898
899           lhs_fvs = exprsFreeVars rule_args     -- Includes template tyvars
900           match_fn rule_arg arg = match menv emptySubstEnv rule_arg arg
901                 where
902                   in_scope = lhs_fvs `unionVarSet` exprFreeVars arg
903                   menv = ME { me_env   = mkRnEnv2 (mkInScopeSet in_scope)
904                             , me_tmpls = mkVarSet rule_bndrs }
905 \end{code}
906