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