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