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