2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
5 Taken quite directly from the Peyton Jones/Lester paper.
8 {-# OPTIONS -fno-warn-incomplete-patterns #-}
9 -- The above warning supression flag is a temporary kludge.
10 -- While working on this module you are encouraged to remove it and fix
11 -- any warnings in the module. See
12 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
15 -- | A module concerned with finding the free variables of an expression.
17 -- * Free variables of expressions and binding groups
18 exprFreeVars, -- CoreExpr -> VarSet -- Find all locally-defined free Ids or tyvars
19 exprsFreeVars, -- [CoreExpr] -> VarSet
20 bindFreeVars, -- CoreBind -> VarSet
22 -- * Selective free variables of expressions
24 exprSomeFreeVars, exprsSomeFreeVars,
25 exprFreeNames, exprsFreeNames,
27 -- * Free variables of Rules, Vars and Ids
28 idRuleVars, idFreeVars, varTypeTyVars,
29 ruleRhsFreeVars, rulesFreeVars,
30 ruleLhsFreeNames, ruleLhsFreeIds,
32 -- * Core syntax tree annotation with free variables
33 CoreExprWithFVs, -- = AnnExpr Id VarSet
34 CoreBindWithFVs, -- = AnnBind Id VarSet
35 freeVars, -- CoreExpr -> CoreExprWithFVs
36 freeVarsOf -- CoreExprWithFVs -> IdSet
39 #include "HsVersions.h"
55 %************************************************************************
57 \section{Finding the free variables of an expression}
59 %************************************************************************
61 This function simply finds the free variables of an expression.
62 So far as type variables are concerned, it only finds tyvars that are
64 * free in type arguments,
65 * free in the type of a binder,
67 but not those that are free in the type of variable occurrence.
70 -- | Find all locally-defined free Ids or type variables in an expression
71 exprFreeVars :: CoreExpr -> VarSet
72 exprFreeVars = exprSomeFreeVars isLocalVar
74 -- | Find all locally-defined free Ids or type variables in several expressions
75 exprsFreeVars :: [CoreExpr] -> VarSet
76 exprsFreeVars = foldr (unionVarSet . exprFreeVars) emptyVarSet
78 -- | Find all locally defined free Ids in a binding group
79 bindFreeVars :: CoreBind -> VarSet
80 bindFreeVars (NonRec _ r) = exprFreeVars r
81 bindFreeVars (Rec prs) = addBndrs (map fst prs)
82 (foldr (union . rhs_fvs) noVars prs)
83 isLocalVar emptyVarSet
85 -- | Finds free variables in an expression selected by a predicate
86 exprSomeFreeVars :: InterestingVarFun -- ^ Says which 'Var's are interesting
89 exprSomeFreeVars fv_cand e = expr_fvs e fv_cand emptyVarSet
91 -- | Finds free variables in several expressions selected by a predicate
92 exprsSomeFreeVars :: InterestingVarFun -- Says which 'Var's are interesting
95 exprsSomeFreeVars fv_cand = foldr (unionVarSet . exprSomeFreeVars fv_cand) emptyVarSet
97 -- | Predicate on possible free variables: returns @True@ iff the variable is interesting
98 type InterestingVarFun = Var -> Bool
103 type FV = InterestingVarFun
104 -> VarSet -- In scope
105 -> VarSet -- Free vars
107 union :: FV -> FV -> FV
108 union fv1 fv2 fv_cand in_scope = fv1 fv_cand in_scope `unionVarSet` fv2 fv_cand in_scope
111 noVars _ _ = emptyVarSet
113 -- Comment about obselete code
114 -- We used to gather the free variables the RULES at a variable occurrence
115 -- with the following cryptic comment:
116 -- "At a variable occurrence, add in any free variables of its rule rhss
117 -- Curiously, we gather the Id's free *type* variables from its binding
118 -- site, but its free *rule-rhs* variables from its usage sites. This
119 -- is a little weird. The reason is that the former is more efficient,
120 -- but the latter is more fine grained, and a makes a difference when
121 -- a variable mentions itself one of its own rule RHSs"
122 -- Not only is this "weird", but it's also pretty bad because it can make
123 -- a function seem more recursive than it is. Suppose
126 -- RULE g x = ...f...
127 -- Then f is not mentioned in its own RHS, and needn't be a loop breaker
128 -- (though g may be). But if we collect the rule fvs from g's occurrence,
129 -- it looks as if f mentions itself. (This bites in the eftInt/eftIntFB
130 -- code in GHC.Enum.)
132 -- Anyway, it seems plain wrong. The RULE is like an extra RHS for the
133 -- function, so its free variables belong at the definition site.
135 -- Deleted code looked like
136 -- foldVarSet add_rule_var var_itself_set (idRuleVars var)
137 -- add_rule_var var set | keep_it fv_cand in_scope var = extendVarSet set var
142 oneVar var fv_cand in_scope
144 if keep_it fv_cand in_scope var
148 someVars :: VarSet -> FV
149 someVars vars fv_cand in_scope
150 = filterVarSet (keep_it fv_cand in_scope) vars
152 keep_it :: InterestingVarFun -> VarSet -> Var -> Bool
153 keep_it fv_cand in_scope var
154 | var `elemVarSet` in_scope = False
159 addBndr :: CoreBndr -> FV -> FV
160 addBndr bndr fv fv_cand in_scope
161 = someVars (varTypeTyVars bndr) fv_cand in_scope
162 -- Include type varibles in the binder's type
163 -- (not just Ids; coercion variables too!)
164 `unionVarSet` fv fv_cand (in_scope `extendVarSet` bndr)
166 addBndrs :: [CoreBndr] -> FV -> FV
167 addBndrs bndrs fv = foldr addBndr fv bndrs
172 expr_fvs :: CoreExpr -> FV
174 expr_fvs (Type ty) = someVars (tyVarsOfType ty)
175 expr_fvs (Var var) = oneVar var
176 expr_fvs (Lit _) = noVars
177 expr_fvs (Note _ expr) = expr_fvs expr
178 expr_fvs (App fun arg) = expr_fvs fun `union` expr_fvs arg
179 expr_fvs (Lam bndr body) = addBndr bndr (expr_fvs body)
180 expr_fvs (Cast expr co) = expr_fvs expr `union` someVars (tyVarsOfType co)
182 expr_fvs (Case scrut bndr ty alts)
183 = expr_fvs scrut `union` someVars (tyVarsOfType ty) `union` addBndr bndr
184 (foldr (union . alt_fvs) noVars alts)
186 alt_fvs (_, bndrs, rhs) = addBndrs bndrs (expr_fvs rhs)
188 expr_fvs (Let (NonRec bndr rhs) body)
189 = rhs_fvs (bndr, rhs) `union` addBndr bndr (expr_fvs body)
191 expr_fvs (Let (Rec pairs) body)
192 = addBndrs (map fst pairs)
193 (foldr (union . rhs_fvs) (expr_fvs body) pairs)
196 rhs_fvs :: (Id,CoreExpr) -> FV
197 rhs_fvs (bndr, rhs) = expr_fvs rhs `union` someVars (bndrRuleVars bndr)
198 -- Treat any RULES as extra RHSs of the binding
201 exprs_fvs :: [CoreExpr] -> FV
202 exprs_fvs exprs = foldr (union . expr_fvs) noVars exprs
206 %************************************************************************
210 %************************************************************************
213 -- | Similar to 'exprFreeNames'. However, this is used when deciding whether
214 -- a rule is an orphan. In particular, suppose that T is defined in this
215 -- module; we want to avoid declaring that a rule like:
217 -- > fromIntegral T = fromIntegral_T
219 -- is an orphan. Of course it isn't, and declaring it an orphan would
220 -- make the whole module an orphan module, which is bad.
221 ruleLhsFreeNames :: CoreRule -> NameSet
222 ruleLhsFreeNames (BuiltinRule { ru_fn = fn }) = unitNameSet fn
223 ruleLhsFreeNames (Rule { ru_fn = fn, ru_args = tpl_args })
224 = addOneToNameSet (exprsFreeNames tpl_args) fn
226 -- | Finds the free /external/ names of an expression, notably
227 -- including the names of type constructors (which of course do not show
228 -- up in 'exprFreeVars').
229 exprFreeNames :: CoreExpr -> NameSet
230 -- There's no need to delete local binders, because they will all
231 -- be /internal/ names.
236 | isExternalName n = unitNameSet n
237 | otherwise = emptyNameSet
239 go (Lit _) = emptyNameSet
240 go (Type ty) = tyClsNamesOfType ty -- Don't need free tyvars
241 go (App e1 e2) = go e1 `unionNameSets` go e2
242 go (Lam v e) = go e `delFromNameSet` idName v
244 go (Cast e co) = go e `unionNameSets` tyClsNamesOfType co
245 go (Let (NonRec _ r) e) = go e `unionNameSets` go r
246 go (Let (Rec prs) e) = exprsFreeNames (map snd prs) `unionNameSets` go e
247 go (Case e _ ty as) = go e `unionNameSets` tyClsNamesOfType ty
248 `unionNameSets` unionManyNameSets (map go_alt as)
250 go_alt (_,_,r) = go r
252 -- | Finds the free /external/ names of several expressions: see 'exprFreeNames' for details
253 exprsFreeNames :: [CoreExpr] -> NameSet
254 exprsFreeNames es = foldr (unionNameSets . exprFreeNames) emptyNameSet es
257 %************************************************************************
259 \section[freevars-everywhere]{Attaching free variables to every sub-expression}
261 %************************************************************************
264 -- | Those variables free in the right hand side of a rule
265 ruleRhsFreeVars :: CoreRule -> VarSet
266 ruleRhsFreeVars (BuiltinRule {}) = noFVs
267 ruleRhsFreeVars (Rule { ru_fn = fn, ru_bndrs = bndrs, ru_rhs = rhs })
268 = delFromUFM fvs fn -- Note [Rule free var hack]
270 fvs = addBndrs bndrs (expr_fvs rhs) isLocalVar emptyVarSet
272 -- | Those variables free in the both the left right hand sides of a rule
273 ruleFreeVars :: CoreRule -> VarSet
274 ruleFreeVars (Rule { ru_fn = fn, ru_bndrs = bndrs, ru_rhs = rhs, ru_args = args })
275 = delFromUFM fvs fn -- Note [Rule free var hack]
277 fvs = addBndrs bndrs (exprs_fvs (rhs:args)) isLocalVar emptyVarSet
279 -- | Those variables free in the right hand side of several rules
280 rulesFreeVars :: [CoreRule] -> VarSet
281 rulesFreeVars rules = foldr (unionVarSet . ruleFreeVars) emptyVarSet rules
283 ruleLhsFreeIds :: CoreRule -> VarSet
284 -- ^ This finds all locally-defined free Ids on the left hand side of a rule
285 ruleLhsFreeIds (BuiltinRule {}) = noFVs
286 ruleLhsFreeIds (Rule { ru_bndrs = bndrs, ru_args = args })
287 = addBndrs bndrs (exprs_fvs args) isLocalId emptyVarSet
290 Note [Rule free var hack]
291 ~~~~~~~~~~~~~~~~~~~~~~~~~
292 Don't include the Id in its own rhs free-var set.
293 Otherwise the occurrence analyser makes bindings recursive
294 that shoudn't be. E.g.
295 RULE: f (f x y) z ==> f x (f y z)
297 Also since rule_fn is a Name, not a Var, we have to use the grungy delUFM.
299 %************************************************************************
301 \section[freevars-everywhere]{Attaching free variables to every sub-expression}
303 %************************************************************************
305 The free variable pass annotates every node in the expression with its
306 NON-GLOBAL free variables and type variables.
309 -- | Every node in a binding group annotated with its
310 -- (non-global) free variables, both Ids and TyVars
311 type CoreBindWithFVs = AnnBind Id VarSet
312 -- | Every node in an expression annotated with its
313 -- (non-global) free variables, both Ids and TyVars
314 type CoreExprWithFVs = AnnExpr Id VarSet
316 freeVarsOf :: CoreExprWithFVs -> IdSet
317 -- ^ Inverse function to 'freeVars'
318 freeVarsOf (free_vars, _) = free_vars
323 aFreeVar :: Var -> VarSet
324 aFreeVar = unitVarSet
326 unionFVs :: VarSet -> VarSet -> VarSet
327 unionFVs = unionVarSet
329 delBindersFV :: [Var] -> VarSet -> VarSet
330 delBindersFV bs fvs = foldr delBinderFV fvs bs
332 delBinderFV :: Var -> VarSet -> VarSet
333 -- This way round, so we can do it multiple times using foldr
335 -- (b `delBinderFV` s) removes the binder b from the free variable set s,
337 -- (a) the free variables of b's type
338 -- (b) the idSpecVars of b
340 -- This is really important for some lambdas:
341 -- In (\x::a -> x) the only mention of "a" is in the binder.
344 -- let x::a = b in ...
345 -- we should really note that "a" is free in this expression.
346 -- It'll be pinned inside the /\a by the binding for b, but
347 -- it seems cleaner to make sure that a is in the free-var set
348 -- when it is mentioned.
350 -- This also shows up in recursive bindings. Consider:
351 -- /\a -> letrec x::a = x in E
352 -- Now, there are no explicit free type variables in the RHS of x,
353 -- but nevertheless "a" is free in its definition. So we add in
354 -- the free tyvars of the types of the binders, and include these in the
355 -- free vars of the group, attached to the top level of each RHS.
357 -- This actually happened in the defn of errorIO in IOBase.lhs:
358 -- errorIO (ST io) = case (errorIO# io) of
361 -- bottom = bottom -- Never evaluated
363 delBinderFV b s = (s `delVarSet` b) `unionFVs` varTypeTyVars b
364 -- Include coercion variables too!
366 varTypeTyVars :: Var -> TyVarSet
367 -- Find the type variables free in the type of the variable
368 -- Remember, coercion variables can mention type variables...
370 | isLocalId var || isCoVar var = tyVarsOfType (idType var)
371 | otherwise = emptyVarSet -- Global Ids and non-coercion TyVars
373 idFreeVars :: Id -> VarSet
374 idFreeVars id = ASSERT( isId id) idRuleVars id `unionVarSet` varTypeTyVars id
376 bndrRuleVars ::Var -> VarSet
377 bndrRuleVars v | isTyVar v = emptyVarSet
378 | otherwise = idRuleVars v
380 idRuleVars ::Id -> VarSet
381 idRuleVars id = ASSERT( isId id) specInfoFreeVars (idSpecialisation id)
385 %************************************************************************
387 \subsection{Free variables (and types)}
389 %************************************************************************
392 freeVars :: CoreExpr -> CoreExprWithFVs
393 -- ^ Annotate a 'CoreExpr' with its (non-global) free type and value variables at every tree node
397 -- ToDo: insert motivating example for why we *need*
398 -- to include the idSpecVars in the FV list.
399 -- Actually [June 98] I don't think it's necessary
400 -- fvs = fvs_v `unionVarSet` idSpecVars v
402 fvs | isLocalVar v = aFreeVar v
405 freeVars (Lit lit) = (noFVs, AnnLit lit)
406 freeVars (Lam b body)
407 = (b `delBinderFV` freeVarsOf body', AnnLam b body')
409 body' = freeVars body
411 freeVars (App fun arg)
412 = (freeVarsOf fun2 `unionFVs` freeVarsOf arg2, AnnApp fun2 arg2)
417 freeVars (Case scrut bndr ty alts)
418 = ((bndr `delBinderFV` alts_fvs) `unionFVs` freeVarsOf scrut2 `unionFVs` tyVarsOfType ty,
419 AnnCase scrut2 bndr ty alts2)
421 scrut2 = freeVars scrut
423 (alts_fvs_s, alts2) = mapAndUnzip fv_alt alts
424 alts_fvs = foldr1 unionFVs alts_fvs_s
426 fv_alt (con,args,rhs) = (delBindersFV args (freeVarsOf rhs2),
431 freeVars (Let (NonRec binder rhs) body)
432 = (freeVarsOf rhs2 `unionFVs` body_fvs `unionFVs` bndrRuleVars binder,
433 -- Remember any rules; cf rhs_fvs above
434 AnnLet (AnnNonRec binder rhs2) body2)
437 body2 = freeVars body
438 body_fvs = binder `delBinderFV` freeVarsOf body2
440 freeVars (Let (Rec binds) body)
441 = (delBindersFV binders all_fvs,
442 AnnLet (AnnRec (binders `zip` rhss2)) body2)
444 (binders, rhss) = unzip binds
446 rhss2 = map freeVars rhss
447 rhs_body_fvs = foldr (unionFVs . freeVarsOf) body_fvs rhss2
448 all_fvs = foldr (unionFVs . idRuleVars) rhs_body_fvs binders
449 -- The "delBinderFV" happens after adding the idSpecVars,
450 -- since the latter may add some of the binders as fvs
452 body2 = freeVars body
453 body_fvs = freeVarsOf body2
456 freeVars (Cast expr co)
457 = (freeVarsOf expr2 `unionFVs` cfvs, AnnCast expr2 co)
459 expr2 = freeVars expr
460 cfvs = tyVarsOfType co
462 freeVars (Note other_note expr)
463 = (freeVarsOf expr2, AnnNote other_note expr2)
465 expr2 = freeVars expr
467 freeVars (Type ty) = (tyVarsOfType ty, AnnType ty)