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