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