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