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