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