Add missing case for eq_note.
[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 (Note _ e1) e2 = match menv subst e1 e2
492 match menv subst e1 (Note _ e2) = match menv subst e1 e2
493       -- Ignore notes in both template and thing to be matched
494       -- See Note [Notes in RULE matching]
495
496 match menv subst e1 (Var v2)      -- Note [Expanding variables]
497   | not (locallyBoundR rn_env v2) -- Note [Do not expand locally-bound variables]
498   , Just e2' <- expandId v2'
499   = match (menv { me_env = nukeRnEnvR rn_env }) subst e1 e2'
500   where
501     v2'    = lookupRnInScope rn_env v2
502     rn_env = me_env menv
503         -- Notice that we look up v2 in the in-scope set
504         -- See Note [Lookup in-scope]
505         -- No need to apply any renaming first (hence no rnOccR)
506         -- becuase of the not-locallyBoundR
507
508 match menv (tv_subst, id_subst, binds) e1 (Let bind e2)
509   | all freshly_bound bndrs     -- See Note [Matching lets]
510   , not (any (locallyBoundR rn_env) bind_fvs)
511   = match (menv { me_env = rn_env' }) 
512           (tv_subst, id_subst, binds `snocOL` bind')
513           e1 e2'
514   where
515     rn_env   = me_env menv
516     bndrs    = bindersOf  bind
517     bind_fvs = varSetElems (bindFreeVars bind)
518     freshly_bound x = not (x `rnInScope` rn_env)
519     bind'   = bind
520     e2'     = e2
521     rn_env' = extendRnInScopeList rn_env bndrs
522
523 match _ subst (Lit lit1) (Lit lit2)
524   | lit1 == lit2
525   = Just subst
526
527 match menv subst (App f1 a1) (App f2 a2)
528   = do  { subst' <- match menv subst f1 f2
529         ; match menv subst' a1 a2 }
530
531 match menv subst (Lam x1 e1) (Lam x2 e2)
532   = match menv' subst e1 e2
533   where
534     menv' = menv { me_env = rnBndr2 (me_env menv) x1 x2 }
535
536 -- This rule does eta expansion
537 --              (\x.M)  ~  N    iff     M  ~  N x
538 -- It's important that this is *after* the let rule,
539 -- so that      (\x.M)  ~  (let y = e in \y.N)
540 -- does the let thing, and then gets the lam/lam rule above
541 match menv subst (Lam x1 e1) e2
542   = match menv' subst e1 (App e2 (varToCoreExpr new_x))
543   where
544     (rn_env', new_x) = rnBndrL (me_env menv) x1
545     menv' = menv { me_env = rn_env' }
546
547 -- Eta expansion the other way
548 --      M  ~  (\y.N)    iff   M y     ~  N
549 match menv subst e1 (Lam x2 e2)
550   = match menv' subst (App e1 (varToCoreExpr new_x)) e2
551   where
552     (rn_env', new_x) = rnBndrR (me_env menv) x2
553     menv' = menv { me_env = rn_env' }
554
555 match menv subst (Case e1 x1 ty1 alts1) (Case e2 x2 ty2 alts2)
556   = do  { subst1 <- match_ty menv subst ty1 ty2
557         ; subst2 <- match menv subst1 e1 e2
558         ; let menv' = menv { me_env = rnBndr2 (me_env menv) x1 x2 }
559         ; match_alts menv' subst2 alts1 alts2   -- Alts are both sorted
560         }
561
562 match menv subst (Type ty1) (Type ty2)
563   = match_ty menv subst ty1 ty2
564
565 match menv subst (Cast e1 co1) (Cast e2 co2)
566   = do  { subst1 <- match_ty menv subst co1 co2
567         ; match menv subst1 e1 e2 }
568
569 -- Everything else fails
570 match _ _ _e1 _e2 = -- pprTrace "Failing at" ((text "e1:" <+> ppr _e1) $$ (text "e2:" <+> ppr _e2)) $ 
571                          Nothing
572
573 ------------------------------------------
574 match_var :: MatchEnv
575           -> SubstEnv
576           -> Var                -- Template
577           -> CoreExpr           -- Target
578           -> Maybe SubstEnv
579 match_var menv subst@(tv_subst, id_subst, binds) v1 e2
580   | v1' `elemVarSet` me_tmpls menv
581   = case lookupVarEnv id_subst v1' of
582         Nothing | any (inRnEnvR rn_env) (varSetElems (exprFreeVars e2))
583                 -> Nothing      -- Occurs check failure
584                 -- e.g. match forall a. (\x-> a x) against (\y. y y)
585
586                 | otherwise     -- No renaming to do on e2, because no free var
587                                 -- of e2 is in the rnEnvR of the envt
588                 -- Note [Matching variable types]
589                 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
590                 -- However, we must match the *types*; e.g.
591                 --   forall (c::Char->Int) (x::Char). 
592                 --      f (c x) = "RULE FIRED"
593                 -- We must only match on args that have the right type
594                 -- It's actually quite difficult to come up with an example that shows
595                 -- you need type matching, esp since matching is left-to-right, so type
596                 -- args get matched first.  But it's possible (e.g. simplrun008) and
597                 -- this is the Right Thing to do
598                 -> do   { tv_subst' <- Unify.ruleMatchTyX menv tv_subst (idType v1') (exprType e2)
599                                                 -- c.f. match_ty below
600                         ; return (tv_subst', extendVarEnv id_subst v1' e2, binds) }
601
602         Just e1' | eqExpr (nukeRnEnvL rn_env) e1' e2 
603                  -> Just subst
604
605                  | otherwise
606                  -> Nothing
607
608   | otherwise   -- v1 is not a template variable; check for an exact match with e2
609   = case e2 of
610        Var v2 | v1' == rnOccR rn_env v2 -> Just subst
611        _                                -> Nothing
612
613   where
614     rn_env = me_env menv
615     v1'    = rnOccL rn_env v1   
616         -- If the template is
617         --      forall x. f x (\x -> x) = ...
618         -- Then the x inside the lambda isn't the 
619         -- template x, so we must rename first!
620                                 
621
622 ------------------------------------------
623 match_alts :: MatchEnv
624       -> SubstEnv
625       -> [CoreAlt]              -- Template
626       -> [CoreAlt]              -- Target
627       -> Maybe SubstEnv
628 match_alts _ subst [] []
629   = return subst
630 match_alts menv subst ((c1,vs1,r1):alts1) ((c2,vs2,r2):alts2)
631   | c1 == c2
632   = do  { subst1 <- match menv' subst r1 r2
633         ; match_alts menv subst1 alts1 alts2 }
634   where
635     menv' :: MatchEnv
636     menv' = menv { me_env = rnBndrs2 (me_env menv) vs1 vs2 }
637
638 match_alts _ _ _ _
639   = Nothing
640 \end{code}
641
642 Matching Core types: use the matcher in TcType.
643 Notice that we treat newtypes as opaque.  For example, suppose 
644 we have a specialised version of a function at a newtype, say 
645         newtype T = MkT Int
646 We only want to replace (f T) with f', not (f Int).
647
648 \begin{code}
649 ------------------------------------------
650 match_ty :: MatchEnv
651          -> SubstEnv
652          -> Type                -- Template
653          -> Type                -- Target
654          -> Maybe SubstEnv
655 match_ty menv (tv_subst, id_subst, binds) ty1 ty2
656   = do  { tv_subst' <- Unify.ruleMatchTyX menv tv_subst ty1 ty2
657         ; return (tv_subst', id_subst, binds) }
658 \end{code}
659
660 Note [Expanding variables]
661 ~~~~~~~~~~~~~~~~~~~~~~~~~~
662 Here is another Very Important rule: if the term being matched is a
663 variable, we expand it so long as its unfolding is "expandable". (Its
664 occurrence information is not necessarily up to date, so we don't use
665 it.)  By "expandable" we mean a WHNF or a "constructor-like" application.
666 This is the key reason for "constructor-like" Ids.  If we have
667      {-# NOINLINE [1] CONLIKE g #-}
668      {-# RULE f (g x) = h x #-}
669 then in the term
670    let v = g 3 in ....(f v)....
671 we want to make the rule fire, to replace (f v) with (h 3). 
672
673 Note [Do not expand locally-bound variables]
674 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
675 Do *not* expand locally-bound variables, else there's a worry that the
676 unfolding might mention variables that are themselves renamed.
677 Example
678           case x of y { (p,q) -> ...y... }
679 Don't expand 'y' to (p,q) because p,q might themselves have been 
680 renamed.  Essentially we only expand unfoldings that are "outside" 
681 the entire match.
682
683 Hence, (a) the guard (not (isLocallyBoundR v2))
684        (b) when we expand we nuke the renaming envt (nukeRnEnvR).
685
686 Note [Notes in RULE matching]
687 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
688 Look through Notes in both template and expression being matched.  In
689 particular, we don't want to be confused by InlineMe notes.  Maybe we
690 should be more careful about profiling notes, but for now I'm just
691 riding roughshod over them.  cf Note [Notes in call patterns] in
692 SpecConstr
693
694 Note [Matching lets]
695 ~~~~~~~~~~~~~~~~~~~~
696 Matching a let-expression.  Consider
697         RULE forall x.  f (g x) = <rhs>
698 and target expression
699         f (let { w=R } in g E))
700 Then we'd like the rule to match, to generate
701         let { w=R } in (\x. <rhs>) E
702 In effect, we want to float the let-binding outward, to enable
703 the match to happen.  This is the WHOLE REASON for accumulating
704 bindings in the SubstEnv
705
706 We can only do this if
707         (a) Widening the scope of w does not capture any variables
708             We use a conservative test: w is not already in scope
709             If not, we clone the binders, and substitute
710         (b) The free variables of R are not bound by the part of the
711             target expression outside the let binding; e.g.
712                 f (\v. let w = v+1 in g E)
713             Here we obviously cannot float the let-binding for w.
714
715 You may think rule (a) would never apply, because rule matching is
716 mostly invoked from the simplifier, when we have just run substExpr 
717 over the argument, so there will be no shadowing anyway.
718 The fly in the ointment is that the forall'd variables of the
719 RULE itself are considered in scope.
720
721 I though of various ways to solve (a).  One plan was to 
722 clone the binders if they are in scope.  But watch out!
723         (let x=y+1 in let z=x+1 in (z,z)
724                 --> should match (p,p) but watch out that 
725                     the use of x on z's rhs is OK!
726 If we clone x, then the let-binding for 'z' is then caught by (b), 
727 at least unless we elaborate the RnEnv stuff a bit.
728
729 So for we simply fail to match unless both (a) and (b) hold.
730
731 Other cases to think about
732         (let x=y+1 in \x. (x,x))
733                 --> let x=y+1 in (\x1. (x1,x1))
734         (\x. let x = y+1 in (x,x))
735                 --> let x1 = y+1 in (\x. (x1,x1)
736         (let x=y+1 in (x,x), let x=y-1 in (x,x))
737                 --> let x=y+1 in let x1=y-1 in ((x,x),(x1,x1))
738
739
740 Note [Lookup in-scope]
741 ~~~~~~~~~~~~~~~~~~~~~~
742 Consider this example
743         foo :: Int -> Maybe Int -> Int
744         foo 0 (Just n) = n
745         foo m (Just n) = foo (m-n) (Just n)
746
747 SpecConstr sees this fragment:
748
749         case w_smT of wild_Xf [Just A] {
750           Data.Maybe.Nothing -> lvl_smf;
751           Data.Maybe.Just n_acT [Just S(L)] ->
752             case n_acT of wild1_ams [Just A] { GHC.Base.I# y_amr [Just L] ->
753             \$wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf
754             }};
755
756 and correctly generates the rule
757
758         RULES: "SC:$wfoo1" [0] __forall {y_amr [Just L] :: GHC.Prim.Int#
759                                           sc_snn :: GHC.Prim.Int#}
760           \$wfoo_smW sc_snn (Data.Maybe.Just @ GHC.Base.Int (GHC.Base.I# y_amr))
761           = \$s\$wfoo_sno y_amr sc_snn ;]
762
763 BUT we must ensure that this rule matches in the original function!
764 Note that the call to \$wfoo is
765             \$wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf
766
767 During matching we expand wild_Xf to (Just n_acT).  But then we must also
768 expand n_acT to (I# y_amr).  And we can only do that if we look up n_acT
769 in the in-scope set, because in wild_Xf's unfolding it won't have an unfolding
770 at all. 
771
772 That is why the 'lookupRnInScope' call in the (Var v2) case of 'match'
773 is so important.
774
775 \begin{code}
776 eqExpr :: RnEnv2 -> CoreExpr -> CoreExpr -> Bool
777 -- ^ A kind of shallow equality used in rule matching, so does 
778 -- /not/ look through newtypes or predicate types
779
780 eqExpr env (Var v1) (Var v2)
781   | rnOccL env v1 == rnOccR env v2
782   = True
783
784 -- The next two rules expand non-local variables
785 -- C.f. Note [Expanding variables]
786 -- and  Note [Do not expand locally-bound variables]
787 eqExpr env (Var v1) e2
788   | not (locallyBoundL env v1)
789   , Just e1' <- expandId (lookupRnInScope env v1)
790   = eqExpr (nukeRnEnvL env) e1' e2
791
792 eqExpr env e1 (Var v2)
793   | not (locallyBoundR env v2)
794   , Just e2' <- expandId (lookupRnInScope env v2)
795   = eqExpr (nukeRnEnvR env) e1 e2'
796
797 eqExpr _   (Lit lit1)    (Lit lit2)    = lit1 == lit2
798 eqExpr env (App f1 a1)   (App f2 a2)   = eqExpr env f1 f2 && eqExpr env a1 a2
799 eqExpr env (Lam v1 e1)   (Lam v2 e2)   = eqExpr (rnBndr2 env v1 v2) e1 e2
800 eqExpr env (Note n1 e1)  (Note n2 e2)  = eq_note env n1 n2 && eqExpr env e1 e2
801 eqExpr env (Cast e1 co1) (Cast e2 co2) = tcEqTypeX env co1 co2 && eqExpr env e1 e2
802 eqExpr env (Type t1)     (Type t2)     = tcEqTypeX env t1 t2
803
804 eqExpr env (Let (NonRec v1 r1) e1)
805            (Let (NonRec v2 r2) e2) =  eqExpr env r1 r2 
806                                    && eqExpr (rnBndr2 env v1 v2) e1 e2
807 eqExpr env (Let (Rec ps1) e1)
808            (Let (Rec ps2) e2)      =  equalLength ps1 ps2
809                                    && and (zipWith eq_rhs ps1 ps2)
810                                    && eqExpr env' e1 e2
811                                    where
812                                       env' = foldl2 rn_bndr2 env ps2 ps2
813                                       rn_bndr2 env (b1,_) (b2,_) = rnBndr2 env b1 b2
814                                       eq_rhs       (_,r1) (_,r2) = eqExpr env' r1 r2
815 eqExpr env (Case e1 v1 t1 a1)
816            (Case e2 v2 t2 a2) =  eqExpr env e1 e2
817                               && tcEqTypeX env t1 t2                      
818                               && equalLength a1 a2
819                               && and (zipWith (eq_alt env') a1 a2)
820                               where
821                                 env' = rnBndr2 env v1 v2
822
823 eqExpr _   _             _             = False
824
825 eq_alt :: RnEnv2 -> CoreAlt -> CoreAlt -> Bool
826 eq_alt env (c1,vs1,r1) (c2,vs2,r2) = c1==c2 && eqExpr (rnBndrs2 env vs1  vs2) r1 r2
827
828 eq_note :: RnEnv2 -> Note -> Note -> Bool
829 eq_note _ (SCC cc1)     (SCC cc2)      = cc1 == cc2
830 eq_note _ (CoreNote s1) (CoreNote s2)  = s1 == s2
831 eq_note _ (InlineMe)    (InlineMe)     = True
832 eq_note _ _             _              = False
833 \end{code}
834
835 Auxiliary functions
836
837 \begin{code}
838 locallyBoundL, locallyBoundR :: RnEnv2 -> Var -> Bool
839 locallyBoundL rn_env v = inRnEnvL rn_env v
840 locallyBoundR rn_env v = inRnEnvR rn_env v
841
842
843 expandId :: Id -> Maybe CoreExpr
844 expandId id
845   | isExpandableUnfolding unfolding = Just (unfoldingTemplate unfolding)
846   | otherwise                       = Nothing
847   where
848     unfolding = idUnfolding id
849 \end{code}
850
851 %************************************************************************
852 %*                                                                      *
853                    Rule-check the program                                                                               
854 %*                                                                      *
855 %************************************************************************
856
857    We want to know what sites have rules that could have fired but didn't.
858    This pass runs over the tree (without changing it) and reports such.
859
860 \begin{code}
861 -- | Report partial matches for rules beginning with the specified
862 -- string for the purposes of error reporting
863 ruleCheckProgram :: (Activation -> Bool)    -- ^ Rule activation test
864                  -> String                      -- ^ Rule pattern
865                  -> RuleBase                    -- ^ Database of rules
866                  -> [CoreBind]                  -- ^ Bindings to check in
867                  -> SDoc                        -- ^ Resulting check message
868 ruleCheckProgram is_active rule_pat rule_base binds 
869   | isEmptyBag results
870   = text "Rule check results: no rule application sites"
871   | otherwise
872   = vcat [text "Rule check results:",
873           line,
874           vcat [ p $$ line | p <- bagToList results ]
875          ]
876   where
877     results = unionManyBags (map (ruleCheckBind (RuleCheckEnv is_active rule_pat rule_base)) binds)
878     line = text (replicate 20 '-')
879           
880 data RuleCheckEnv = RuleCheckEnv {
881     rc_is_active :: Activation -> Bool, 
882     rc_pattern :: String, 
883     rc_rule_base :: RuleBase
884 }
885
886 ruleCheckBind :: RuleCheckEnv -> CoreBind -> Bag SDoc
887    -- The Bag returned has one SDoc for each call site found
888 ruleCheckBind env (NonRec _ r) = ruleCheck env r
889 ruleCheckBind env (Rec prs)    = unionManyBags [ruleCheck env r | (_,r) <- prs]
890
891 ruleCheck :: RuleCheckEnv -> CoreExpr -> Bag SDoc
892 ruleCheck _   (Var _)       = emptyBag
893 ruleCheck _   (Lit _)       = emptyBag
894 ruleCheck _   (Type _)      = emptyBag
895 ruleCheck env (App f a)     = ruleCheckApp env (App f a) []
896 ruleCheck env (Note _ e)    = ruleCheck env e
897 ruleCheck env (Cast e _)    = ruleCheck env e
898 ruleCheck env (Let bd e)    = ruleCheckBind env bd `unionBags` ruleCheck env e
899 ruleCheck env (Lam _ e)     = ruleCheck env e
900 ruleCheck env (Case e _ _ as) = ruleCheck env e `unionBags` 
901                                 unionManyBags [ruleCheck env r | (_,_,r) <- as]
902
903 ruleCheckApp :: RuleCheckEnv -> Expr CoreBndr -> [Arg CoreBndr] -> Bag SDoc
904 ruleCheckApp env (App f a) as = ruleCheck env a `unionBags` ruleCheckApp env f (a:as)
905 ruleCheckApp env (Var f) as   = ruleCheckFun env f as
906 ruleCheckApp env other _      = ruleCheck env other
907 \end{code}
908
909 \begin{code}
910 ruleCheckFun :: RuleCheckEnv -> Id -> [CoreExpr] -> Bag SDoc
911 -- Produce a report for all rules matching the predicate
912 -- saying why it doesn't match the specified application
913
914 ruleCheckFun env fn args
915   | null name_match_rules = emptyBag
916   | otherwise             = unitBag (ruleAppCheck_help (rc_is_active env) fn args name_match_rules)
917   where
918     name_match_rules = filter match (getRules (rc_rule_base env) fn)
919     match rule = (rc_pattern env) `isPrefixOf` unpackFS (ruleName rule)
920
921 ruleAppCheck_help :: (Activation -> Bool) -> Id -> [CoreExpr] -> [CoreRule] -> SDoc
922 ruleAppCheck_help is_active fn args rules
923   =     -- The rules match the pattern, so we want to print something
924     vcat [text "Expression:" <+> ppr (mkApps (Var fn) args),
925           vcat (map check_rule rules)]
926   where
927     n_args = length args
928     i_args = args `zip` [1::Int ..]
929     rough_args = map roughTopName args
930
931     check_rule rule = rule_herald rule <> colon <+> rule_info rule
932
933     rule_herald (BuiltinRule { ru_name = name })
934         = ptext (sLit "Builtin rule") <+> doubleQuotes (ftext name)
935     rule_herald (Rule { ru_name = name })
936         = ptext (sLit "Rule") <+> doubleQuotes (ftext name)
937
938     rule_info rule
939         | Just _ <- matchRule noBlackList emptyInScopeSet args rough_args rule
940         = text "matches (which is very peculiar!)"
941
942     rule_info (BuiltinRule {}) = text "does not match"
943
944     rule_info (Rule { ru_act = act, 
945                       ru_bndrs = rule_bndrs, ru_args = rule_args})
946         | not (is_active act)    = text "active only in later phase"
947         | n_args < n_rule_args        = text "too few arguments"
948         | n_mismatches == n_rule_args = text "no arguments match"
949         | n_mismatches == 0           = text "all arguments match (considered individually), but rule as a whole does not"
950         | otherwise                   = text "arguments" <+> ppr mismatches <+> text "do not match (1-indexing)"
951         where
952           n_rule_args  = length rule_args
953           n_mismatches = length mismatches
954           mismatches   = [i | (rule_arg, (arg,i)) <- rule_args `zip` i_args,
955                               not (isJust (match_fn rule_arg arg))]
956
957           lhs_fvs = exprsFreeVars rule_args     -- Includes template tyvars
958           match_fn rule_arg arg = match menv emptySubstEnv rule_arg arg
959                 where
960                   in_scope = lhs_fvs `unionVarSet` exprFreeVars arg
961                   menv = ME { me_env   = mkRnEnv2 (mkInScopeSet in_scope)
962                             , me_tmpls = mkVarSet rule_bndrs }
963 \end{code}
964