Debian Codegraph @

src/com/google/javascript/jscomp/ShadowVariables.java

raw symbols SCIP
1 /*
2 * Copyright 2011 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp;
18
19 import com.google.common.collect.HashMultimap;
20 import com.google.common.collect.Maps;
21 import com.google.common.collect.Multimap;
22 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
23 import com.google.javascript.jscomp.NodeTraversal.ScopedCallback;
24 import com.google.javascript.jscomp.RenameVars.Assignment;
25 import com.google.javascript.jscomp.Scope.Var;
26 import com.google.javascript.rhino.Node;
27
28 import java.util.Collection;
29 import java.util.Iterator;
30 import java.util.Map;
31 import java.util.SortedSet;
32
33 /**
34 * Tries to compute a list of variables that can shadow a variable in the
35 * outer scope.
36 *
37 * For example:
38 *
39 * <code>
40 * var a = function() {
41 * var b = getB();
42 * b();
43 * return function(y) {};
44 * };
45 * </code>
46 *
47 * Normally, b would be mapped to variable L0, y would be L1.
48 *
49 * Instead we are going to make y shadows L0 in hope of using less variables
50 * and reusing frequently used local names.
51 *
52 */
53 class ShadowVariables implements CompilerPass {
54
55 // Keep a map of Upward Referencing name nodes of each scope.
56 // A name is upward referencing name of a scope if:
57 //
58 // 1) It refers to (or defines) a name that is defined in the current
59 // scope or any scope above the current scope that isn't the
60 // global scope.
61 //
62 // 2) It is a upward referencing name of a child scope of this scope.
63 //
64 // Example:
65 // var x; var y; function foo(a) { function bar(b) { x, a } }
66 // The upward referencing names in scope 'foo' is bar, b, x and a;
67 // The key to this map is the root node of the scope.
68 //
69 // We can see that for any variable x in the current scope, we can shadow
70 // a variable y in an outer scope given that y is not a upward referencing
71 // name of the current scope.
72
73 // TODO(user): Maps scope to string instead of Node to string.
74 // Make sure of scope memorization to minimize scope creation cost.
75 private final Multimap<Node, String> scopeUpRefMap = HashMultimap.create();
76
77 // Maps all local Scope.Var to all of its referencing NAME node
78 // in any scope.
79 private final Multimap<Var, Node> varToNameUsage = HashMultimap.create();
80
81 private final AbstractCompiler compiler;
82
83 // All the information used for renaming.
84 private final SortedSet<Assignment> varsByFrequency;
85 private final Map<String, Assignment> assignments;
86 private final Map<Node, String> oldPseudoNameMap;
87 private final Map<Node, String> deltaPseudoNameMap;
88
89
90 /**
91 * @param assignments Map of old variable names to its assignment Objects.
92 * @param varsByFrequency Sorted variable assignments by Frequency.
93 * @param pseudoNameMap The current pseudo name map so this pass can update
94 * it accordingly.
95 */
96 ShadowVariables(
97 AbstractCompiler compiler,
98 Map<String, Assignment> assignments,
99 SortedSet<Assignment> varsByFrequency,
100 Map<Node, String> pseudoNameMap) {
101 this.compiler = compiler;
102 this.assignments = assignments;
103 this.varsByFrequency = varsByFrequency;
104 this.oldPseudoNameMap = pseudoNameMap;
105 this.deltaPseudoNameMap = Maps.newLinkedHashMap();
106 }
107
108 @Override
109 public void process(Node externs, Node root) {
110
111 // The algorithm is divided into two stages:
112 //
113 // 1. Information gathering (variable usage, upward referencing)
114 //
115 // 2. Tries to find shadows for each variables, updates the
116 // variable usage frequency map.
117 //
118 // 3. Updates the pseudo naming map if needed.
119 NodeTraversal.traverse(compiler, root, new GatherReferenceInfo());
120 NodeTraversal.traverse(compiler, root, new DoShadowVariables());
121
122 if (oldPseudoNameMap != null) {
123 oldPseudoNameMap.putAll(deltaPseudoNameMap);
124 }
125 }
126
127 private class GatherReferenceInfo extends AbstractPostOrderCallback {
128 @Override
129 public void visit(NodeTraversal t, Node n, Node parent) {
130 // Skipping over non-name nodes and empty function names.
131 if (!NodeUtil.isReferenceName(n)) {
132 return;
133 }
134
135 // We focus on shadowing local variables as their name occurs much more
136 // than global names.
137 // TODO(user): Alternatively, we could experiment with using a local
138 // name to shadow a global variable.
139 if (t.inGlobalScope()) {
140 return;
141 }
142
143 Var var = t.getScope().getVar(n.getString());
144 if (var == null) {
145 // extern name or undefined name.
146 return;
147 }
148
149 if (var.getScope().isGlobal()) {
150 // We will not shadow a global variable name.
151 return;
152 }
153
154 // Using the definition of upward referencing, fill in the map.
155 if (var.getScope() != t.getScope()) {
156 for (Scope s = t.getScope();
157 s != var.getScope() && s.isLocal(); s = s.getParent()) {
158 scopeUpRefMap.put(s.getRootNode(), var.name);
159 }
160 }
161
162 if (var.getScope() == t.getScope()) {
163 scopeUpRefMap.put(t.getScopeRoot(), var.name);
164 }
165
166 // Find in the usage map that tracks a var and all of its usage.
167 varToNameUsage.put(var, n);
168 }
169 }
170
171 private class DoShadowVariables extends AbstractPostOrderCallback
172 implements ScopedCallback {
173
174 @Override
175 public void enterScope(NodeTraversal t) {
176 Scope s = t.getScope();
177 if (!s.isLocal()) {
178 return;
179 }
180
181 // Since we don't shadow global, there is nothing to be done in the
182 // first immediate local scope as well.
183 if (s.getParent().isGlobal()) {
184 return;
185 }
186
187 for (Iterator<Var> vars = s.getVars(); vars.hasNext();) {
188 Var var = vars.next();
189
190 // Don't shadow variables that is bleed-out to fix an IE bug.
191 if (var.isBleedingFunction()) {
192 continue;
193 }
194
195 // Don't shadow an exported local.
196 if (compiler.getCodingConvention().isExported(var.name, s.isLocal())) {
197 continue;
198 }
199
200 // Try to look for the best shadow for the current candidate.
201 Assignment bestShadow = findBestShadow(s);
202 if (bestShadow == null) {
203 continue;
204 }
205
206 // The name assignment being shadowed.
207 Assignment localAssignment = assignments.get(var.getName());
208
209 // Only shadow if this increases the number of occurrences of the
210 // shadowed variable.
211 if (bestShadow.count < localAssignment.count) {
212 continue; // Hope the next local variable would have a smaller count.
213 }
214
215 doShadow(localAssignment, bestShadow, var);
216
217 if (oldPseudoNameMap != null) {
218 String targetPseudoName =
219 oldPseudoNameMap.get(s.getVar(bestShadow.oldName).nameNode);
220 for (Node use : varToNameUsage.get(var)) {
221 deltaPseudoNameMap.put(use, targetPseudoName);
222 }
223 }
224 }
225 }
226
227 @Override
228 public void exitScope(NodeTraversal t) {}
229
230 @Override
231 public void visit(NodeTraversal t, Node n, Node parent) {}
232
233 /**
234 * @returns An assignment that can be used as a shadow for a local variable
235 * in the scope defined by curScopeRoot.
236 */
237 private Assignment findBestShadow(Scope curScope) {
238 // Search for the candidate starting from the most used local.
239 for (Assignment assignment : varsByFrequency) {
240 if (assignment.oldName.startsWith(RenameVars.LOCAL_VAR_PREFIX)) {
241 if (!scopeUpRefMap.get(curScope.getRootNode()).contains(
242 assignment.oldName)) {
243 if (curScope.isDeclared(assignment.oldName, true)) {
244 return assignment;
245 }
246 }
247 }
248 }
249 return null;
250 }
251
252 private void doShadow(Assignment original, Assignment toShadow, Var var) {
253 Scope s = var.getScope();
254 // We are now shadowing 'bestShadow' with localAssignment.
255 // All of the reference NAME node of this variable.
256 Collection<Node> references = varToNameUsage.get(var);
257
258 // First remove both assignments from the sorted list since they need
259 // to be re-sorted.
260 varsByFrequency.remove(original);
261 varsByFrequency.remove(toShadow);
262
263 // Adjust the count offset by the inner scope variable.
264 original.count -= references.size();
265 toShadow.count += references.size();
266
267 // Add it back to the sorted list after re-adjustment.
268 varsByFrequency.add(original);
269 varsByFrequency.add(toShadow);
270
271 // This is an important step. If variable L7 is going to be renamed to
272 // L1, by definition of upward referencing, The name L1 is now in the
273 // set of upward referencing names of the current scope up to the
274 // declaring scope of the best shadow variable.
275 Var shadowed = s.getVar(toShadow.oldName);
276 if (shadowed != null) {
277 for (Scope curScope = s; curScope != shadowed.scope;
278 curScope = curScope.getParent()) {
279 scopeUpRefMap.put(curScope.getRootNode(), toShadow.oldName);
280 }
281 }
282
283 // Mark all the references as shadowed.
284 for (Node n : references) {
285 n.setString(toShadow.oldName);
286 Node cur = n;
287 while(cur != s.getRootNode()) {
288 cur = cur.getParent();
289 if (cur.isFunction()) {
290 scopeUpRefMap.put(cur, toShadow.oldName);
291 }
292 }
293 }
294 }
295 }
296 }