Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2009 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.base.Preconditions;
20 import com.google.common.collect.Lists;
21 import com.google.javascript.jscomp.NodeTraversal.ScopedCallback;
22 import com.google.javascript.rhino.IR;
23 import com.google.javascript.rhino.Node;
24 import java.util.Deque;
25 import java.util.List;
26
27 /**
28 * Optimization for functions that have {@code var_args} or access the
29 * arguments array.
30 *
31 * <p>Example:
32 * <pre>
33 * function() { alert(arguments[0] + argument[1]) }
34 * </pre>
35 * to:
36 * <pre>
37 * function(a, b) { alert(a, b) }
38 * </pre>
39 *
40 * Each newly inserted variable name will be unique very much like the output
41 * of the AST found after the {@link Normalize} pass.
42 *
43 */
44 class OptimizeArgumentsArray implements CompilerPass, ScopedCallback {
45
46 // The arguments object as described by ECMAScript version 3
47 // section 10.1.8
48 private static final String ARGUMENTS = "arguments";
49
50 // To ensure that the newly introduced parameter names are unique. We will
51 // use this string as prefix unless the caller specify a different prefix.
52 private static final String PARAMETER_PREFIX =
53 "JSCompiler_OptimizeArgumentsArray_p";
54
55 // The prefix for the newly introduced parameter name.
56 private final String paramPredix;
57
58 // To make each parameter name unique in the function. We append an
59 // unique integer at the end.
60 private int uniqueId = 0;
61
62 // Reference to the compiler object to notify any changes to source code AST.
63 private final AbstractCompiler compiler;
64
65 // A stack of arguments access list to the corresponding outer functions.
66 private final Deque<List<Node>> argumentsAccessStack = Lists.newLinkedList();
67
68 // This stores a list of argument access in the current scope.
69 private List<Node> currentArgumentsAccess = null;
70
71 /**
72 * Construct this pass and use {@link #PARAMETER_PREFIX} as the prefix for
73 * all parameter names that it introduces.
74 */
75 OptimizeArgumentsArray(AbstractCompiler compiler) {
76 this(compiler, PARAMETER_PREFIX);
77 }
78
79 /**
80 * @param paramPrefix the prefix to use for all parameter names that this
81 * pass introduces
82 */
83 OptimizeArgumentsArray(AbstractCompiler compiler, String paramPrefix) {
84 this.compiler = Preconditions.checkNotNull(compiler);
85 this.paramPredix = Preconditions.checkNotNull(paramPrefix);
86 }
87
88 @Override
89 public void process(Node externs, Node root) {
90 NodeTraversal.traverse(compiler, Preconditions.checkNotNull(root), this);
91 }
92
93 @Override
94 public void enterScope(NodeTraversal traversal) {
95 Preconditions.checkNotNull(traversal);
96
97 // This optimization is valid only within a function so we are going to
98 // skip over the initial entry to the global scope.
99 Node function = traversal.getScopeRoot();
100 if (!function.isFunction()) {
101 return;
102 }
103
104 // Introduces a new access list and stores the access list of the outer
105 // scope in the stack if necessary.
106 if (currentArgumentsAccess != null) {
107 argumentsAccessStack.push(currentArgumentsAccess);
108 }
109 currentArgumentsAccess = Lists.newLinkedList();
110 }
111
112 @Override
113 public void exitScope(NodeTraversal traversal) {
114 Preconditions.checkNotNull(traversal);
115
116 // This is the case when we are exiting the global scope where we had never
117 // collected argument access list. Since we do not perform this optimization
118 // for the global scope, we will skip this exit point.
119 if (currentArgumentsAccess == null) {
120 return;
121 }
122
123 // Attempt to replace the argument access and if the AST has been change,
124 // report back to the compiler.
125 if (tryReplaceArguments(traversal.getScope())) {
126 traversal.getCompiler().reportCodeChange();
127 }
128
129 // After the attempt to replace the arguments. The currentArgumentsAccess
130 // is stale and as we exit the Scope, no longer holds all the access to the
131 // current scope anymore. We'll pop the access list from the outer scope
132 // and set it as currentArgumentsAcess if the outer scope is not the global
133 // scope.
134 if (!argumentsAccessStack.isEmpty()) {
135 currentArgumentsAccess = argumentsAccessStack.pop();
136 } else {
137 currentArgumentsAccess = null;
138 }
139 }
140
141 @Override
142 public boolean shouldTraverse(
143 NodeTraversal nodeTraversal, Node node, Node parent) {
144 // We will continuously recurse down the AST regardless of the node types.
145 return true;
146 }
147
148 @Override
149 public void visit(NodeTraversal traversal, Node node, Node parent) {
150 Preconditions.checkNotNull(traversal);
151 Preconditions.checkNotNull(node);
152
153
154 // Searches for all the references to the arguments array.
155
156 // We don't have an arguments list set up for this scope. This implies we
157 // are currently in the global scope so we will not record any arguments
158 // array access.
159 if (currentArgumentsAccess == null) {
160 return;
161 }
162
163 // Otherwise, we are in a function scope and we should record if the current
164 // name is referring to the implicit arguments array.
165 if (node.isName() && ARGUMENTS.equals(node.getString())) {
166 currentArgumentsAccess.add(node);
167 }
168 }
169
170 /**
171 * Tries to optimize all the arguments array access in this scope by assigning
172 * a name to each element.
173 *
174 * @param scope scope of the function
175 * @return true if any modification has been done to the AST
176 */
177 private boolean tryReplaceArguments(Scope scope) {
178
179 Node parametersList = scope.getRootNode().getFirstChild().getNext();
180 Preconditions.checkState(parametersList.isParamList());
181
182 // Keep track of rather this function modified the AST and needs to be
183 // reported back to the compiler later.
184 boolean changed = false;
185
186 // Number of parameter that can be accessed without using the arguments
187 // array.
188 int numNamedParameter = parametersList.getChildCount();
189
190 // We want to guess what the highest index that has been access from the
191 // arguments array. We will guess that it does not use anything index higher
192 // than the named parameter list first until we see other wise.
193 int highestIndex = numNamedParameter - 1;
194
195 // Iterate through all the references to arguments array in the function to
196 // determine the real highestIndex.
197 for (Node ref : currentArgumentsAccess) {
198
199 Node getElem = ref.getParent();
200
201 // Bail on anything but argument[c] access where c is a constant.
202 // TODO(user): We might not need to bail out all the time, there might
203 // be more cases that we can cover.
204 if (!getElem.isGetElem()) {
205 return false;
206 }
207
208 Node index = ref.getNext();
209
210 // We have something like arguments[x] where x is not a constant. That
211 // means at least one of the access is not known.
212 if (!index.isNumber()) {
213 // TODO(user): Its possible not to give up just yet. The type
214 // inference did a 'semi value propagation'. If we know that string
215 // is never a subclass of the type of the index. We'd know that
216 // it is never 'callee'.
217 return false; // Give up.
218 }
219
220 Node getElemParent = getElem.getParent();
221 // When we have argument[0](), replacing it with a() is semantically
222 // different if argument[0] is a function call that refers to 'this'
223 if (getElemParent.isCall() &&
224 getElemParent.getFirstChild() == getElem) {
225 // TODO(user): We can consider using .call() if aliasing that
226 // argument allows shorter alias for other arguments.
227 return false;
228 }
229
230 // Replace the highest index if we see an access that has a higher index
231 // than all the one we saw before.
232 int value = (int) index.getDouble();
233 if (value > highestIndex) {
234 highestIndex = value;
235 }
236 }
237
238 // Number of extra arguments we need.
239 // For example: function() { arguments[3] } access index 3 so
240 // it will need 4 extra named arguments to changed into:
241 // function(a,b,c,d) { d }.
242 int numExtraArgs = highestIndex - numNamedParameter + 1;
243
244 // Temporary holds the new names as string for quick access later.
245 String[] argNames = new String[numExtraArgs];
246
247 // Insert the formal parameter to the method's signature.
248 // Example: function() --> function(r0, r1, r2)
249 for (int i = 0; i < numExtraArgs; i++) {
250 String name = getNewName();
251 argNames[i] = name;
252 parametersList.addChildrenToBack(IR.name(name));
253 changed = true;
254 }
255
256 // This loop performs the replacement of arguments[x] -> a if x is known.
257 for (Node ref : currentArgumentsAccess) {
258 Node index = ref.getNext();
259
260 // Skip if it is unknown.
261 if (!index.isNumber()) {
262 continue;
263 }
264 int value = (int) index.getDouble();
265
266 // Unnamed parameter.
267 if (value >= numNamedParameter) {
268 ref.getParent().getParent().replaceChild(ref.getParent(),
269 IR.name(argNames[value - numNamedParameter]));
270 } else {
271
272 // Here, for no apparent reason, the user is accessing a named parameter
273 // with arguments[idx]. We can replace it with the actual name for them.
274 Node name = parametersList.getFirstChild();
275
276 // This is a linear search for the actual name from the signature.
277 // It is not necessary to make this fast because chances are the user
278 // will not deliberately write code like this.
279 for (int i = 0; i < value; i++) {
280 name = name.getNext();
281 }
282 ref.getParent().getParent().replaceChild(ref.getParent(),
283 IR.name(name.getString()));
284 }
285 changed = true;
286 }
287
288 return changed;
289 }
290
291 /**
292 * Generate a unique name for the next parameter.
293 */
294 private String getNewName() {
295 return paramPredix + uniqueId++;
296 }
297 }