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