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