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