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