Debian Codegraph @

src/com/google/javascript/jscomp/FunctionArgumentInjector.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 package com.google.javascript.jscomp;
17
18 import com.google.common.base.Preconditions;
19 import com.google.common.base.Predicate;
20 import com.google.common.base.Supplier;
21 import com.google.common.collect.Maps;
22 import com.google.common.collect.Sets;
23 import com.google.javascript.jscomp.NodeUtil.Visitor;
24 import com.google.javascript.rhino.Node;
25 import com.google.javascript.rhino.Token;
26
27 import java.util.LinkedHashMap;
28 import java.util.Map;
29 import java.util.Set;
30
31 /**
32 * A nifty set of functions to deal with the issues of replacing function
33 * parameters with a set of call argument expressions.
34 *
35 * @author [email protected] (John Lenz)
36 */
37 class FunctionArgumentInjector {
38
39 // A string to use to represent "this". Anything that is not a valid
40 // identifier can be used, so we use "this".
41 static final String THIS_MARKER = "this";
42
43 private FunctionArgumentInjector() {
44 // A private constructor to prevent instantiation.
45 }
46
47 /**
48 * With the map provided, replace the names with expression trees.
49 * @param node The root of the node tree within which to perform the
50 * substitutions.
51 * @param parent The parent root node.
52 * @param replacements The map of names to template node trees with which
53 * to replace the name Nodes.
54 * @returns The root node or its replacement.
55 */
56 static Node inject(AbstractCompiler compiler, Node node, Node parent,
57 Map<String, Node> replacements) {
58 return inject(compiler, node, parent, replacements, true);
59 }
60
61 static Node inject(AbstractCompiler compiler, Node node, Node parent,
62 Map<String, Node> replacements, boolean replaceThis) {
63 if (node.isName()) {
64 Node replacementTemplate = replacements.get(node.getString());
65 if (replacementTemplate != null) {
66 // This should not be replacing declared names.
67 Preconditions.checkState(!parent.isFunction()
68 || !parent.isVar()
69 || !parent.isCatch());
70 // The name may need to be replaced more than once,
71 // so we need to clone the node.
72 Node replacement = replacementTemplate.cloneTree();
73 parent.replaceChild(node, replacement);
74 return replacement;
75 }
76 } else if (replaceThis && node.isThis()) {
77 Node replacementTemplate = replacements.get(THIS_MARKER);
78 Preconditions.checkNotNull(replacementTemplate);
79 if (!replacementTemplate.isThis()) {
80 // The name may need to be replaced more than once,
81 // so we need to clone the node.
82 Node replacement = replacementTemplate.cloneTree();
83 parent.replaceChild(node, replacement);
84
85 // Remove the value. This isn't required but it ensures that we won't
86 // inject side-effects multiple times as it will trigger the null
87 // check above if we do.
88 if (NodeUtil.mayHaveSideEffects(replacementTemplate, compiler)) {
89 replacements.remove(THIS_MARKER);
90 }
91
92 return replacement;
93 }
94 } else if (node.isFunction()) {
95 // Once we enter another scope the "this" value changes, don't try
96 // to replace it within an inner scope.
97 replaceThis = false;
98 }
99
100 for (Node c = node.getFirstChild(); c != null; c = c.getNext()) {
101 // We have to reassign c in case it was replaced, because the removed c's
102 // getNext() would no longer be correct.
103 c = inject(compiler, c, node, replacements, replaceThis);
104 }
105
106 return node;
107 }
108
109 /**
110 * Get a mapping for function parameter names to call arguments.
111 */
112 static LinkedHashMap<String, Node> getFunctionCallParameterMap(
113 Node fnNode, Node callNode, Supplier<String> safeNameIdSupplier) {
114 // Create an argName -> expression map
115 // NOTE: A linked map is created here to provide ordering.
116 LinkedHashMap<String, Node> argMap = Maps.newLinkedHashMap();
117
118 // CALL NODE: [ NAME, ARG1, ARG2, ... ]
119 Node cArg = callNode.getFirstChild().getNext();
120 if (cArg != null && NodeUtil.isFunctionObjectCall(callNode)) {
121 argMap.put(THIS_MARKER, cArg);
122 cArg = cArg.getNext();
123 } else {
124 // 'apply' isn't supported yet.
125 Preconditions.checkState(!NodeUtil.isFunctionObjectApply(callNode));
126 argMap.put(THIS_MARKER, NodeUtil.newUndefinedNode(callNode));
127 }
128
129 for (Node fnArg : NodeUtil.getFunctionParameters(fnNode).children()) {
130 if (cArg != null) {
131 argMap.put(fnArg.getString(), cArg);
132 cArg = cArg.getNext();
133 } else {
134 Node srcLocation = callNode;
135 argMap.put(fnArg.getString(), NodeUtil.newUndefinedNode(srcLocation));
136 }
137 }
138
139 // Add temp names for arguments that don't have named parameters in the
140 // called function.
141 while (cArg != null) {
142 String uniquePlaceholder =
143 getUniqueAnonymousParameterName(safeNameIdSupplier);
144 argMap.put(uniquePlaceholder, cArg);
145 cArg = cArg.getNext();
146 }
147
148 return argMap;
149 }
150
151 /**
152 * Parameter names will be name unique when at a later time.
153 */
154 private static String getUniqueAnonymousParameterName(
155 Supplier<String> safeNameIdSupplier) {
156 return "JSCompiler_inline_anon_param_" + safeNameIdSupplier.get();
157 }
158
159 /**
160 * Retrieve a set of names that can not be safely substituted in place.
161 * Example:
162 * function(a) {
163 * a = 0;
164 * }
165 * Inlining this without taking precautions would cause the call site value
166 * to be modified (bad).
167 */
168 static Set<String> findModifiedParameters(Node fnNode) {
169 Set<String> names = getFunctionParameterSet(fnNode);
170 Set<String> unsafeNames = Sets.newHashSet();
171 return findModifiedParameters(
172 fnNode.getLastChild(), null, names, unsafeNames, false);
173 }
174
175 /**
176 * Check for uses of the named value that imply a pass-by-value
177 * parameter is expected. This is used to prevent cases like:
178 *
179 * function (x) {
180 * x=2;
181 * return x;
182 * }
183 *
184 * We don't want "undefined" to be substituted for "x", and get
185 * undefined=2
186 *
187 * @param n The node in question.
188 * @param parent The parent of the node.
189 * @param names The set of names to check.
190 * @param unsafe The set of names that require aliases.
191 * @param inInnerFunction Whether the inspection is occurring on a inner
192 * function.
193 */
194 private static Set<String> findModifiedParameters(
195 Node n, Node parent, Set<String> names, Set<String> unsafe,
196 boolean inInnerFunction) {
197 Preconditions.checkArgument(unsafe != null);
198 if (n.isName()) {
199 if (names.contains(n.getString())) {
200 if (inInnerFunction || canNameValueChange(n, parent)) {
201 unsafe.add(n.getString());
202 }
203 }
204 } else if (n.isFunction()) {
205 // A function parameter can not be replaced with a direct inlined value
206 // if it is referred to by an inner function. The inner function
207 // can out live the call we are replacing, so inner function must
208 // capture a unique name. This approach does not work within loop
209 // bodies so those are forbidden elsewhere.
210 inInnerFunction = true;
211 }
212
213 for (Node c : n.children()) {
214 findModifiedParameters(c, n, names, unsafe, inInnerFunction);
215 }
216
217 return unsafe;
218 }
219
220 /**
221 * This is similar to NodeUtil.isLValue except that object properties and
222 * array member modification aren't important ("o" in "o.a = 2" is still "o"
223 * after assignment, where in as "o = x", "o" is now "x").
224 *
225 * This also looks for the redefinition of a name.
226 * function (x){var x;}
227 *
228 * @param n The NAME node in question.
229 * @param parent The parent of the node.
230 */
231 private static boolean canNameValueChange(Node n, Node parent) {
232 int type = parent.getType();
233 return (type == Token.VAR || type == Token.INC || type == Token.DEC ||
234 (NodeUtil.isAssignmentOp(parent) && parent.getFirstChild() == n));
235 }
236
237 /**
238 * Updates the set of parameter names in set unsafe to include any
239 * arguments from the call site that require aliases.
240 * @param fnNode The FUNCTION node to be inlined.
241 * @param argMap The argument list for the call to fnNode.
242 * @param namesNeedingTemps The set of names to update.
243 */
244 static void maybeAddTempsForCallArguments(
245 Node fnNode, Map<String, Node> argMap, Set<String> namesNeedingTemps,
246 CodingConvention convention) {
247 if (argMap.isEmpty()) {
248 // No arguments to check, we are done.
249 return;
250 }
251
252 Preconditions.checkArgument(fnNode.isFunction());
253 Node block = fnNode.getLastChild();
254
255 Set<String> parameters = argMap.keySet();
256
257 // Get the list of parameters that may need temporaries due to
258 // side-effects.
259 Set<String> namesAfterSideEffects = findParametersReferencedAfterSideEffect(
260 parameters, block);
261
262 // Check for arguments that are evaluated more than once.
263 for (Map.Entry<String, Node> entry : argMap.entrySet()) {
264 String argName = entry.getKey();
265 if (namesNeedingTemps.contains(argName)) {
266 continue;
267 }
268 Node cArg = entry.getValue();
269 boolean safe = true;
270 int references = NodeUtil.getNameReferenceCount(block, argName);
271
272 if (NodeUtil.mayEffectMutableState(cArg) && references > 0) {
273 // Note: Mutable arguments should be assigned to temps, as the
274 // may be within in a loop:
275 // function x(a) {
276 // for(var i=0; i<0; i++) {
277 // foo(a);
278 // }
279 // x( [] );
280 //
281 // The parameter in the call to foo should not become "[]".
282 safe = false;
283 } else if (NodeUtil.mayHaveSideEffects(cArg)) {
284 // Even if there are no references, we still need to evaluate the
285 // expression if it has side-effects.
286 safe = false;
287 } else if (NodeUtil.canBeSideEffected(cArg)
288 && namesAfterSideEffects.contains(argName)) {
289 safe = false;
290 } else if (references > 1) {
291 // Safe is a misnomer, this is a check for "large".
292 switch (cArg.getType()) {
293 case Token.NAME:
294 String name = cArg.getString();
295 safe = !(convention.isExported(name));
296 break;
297 case Token.THIS:
298 safe = true;
299 break;
300 case Token.STRING:
301 safe = (cArg.getString().length() < 2);
302 break;
303 default:
304 safe = NodeUtil.isImmutableValue(cArg);
305 break;
306 }
307 }
308
309 if (!safe) {
310 namesNeedingTemps.add(argName);
311 }
312 }
313 }
314
315 /**
316 * Boot strap a traversal to look for parameters referenced
317 * after a non-local side-effect.
318 * NOTE: This assumes no-inner functions.
319 * @param parameters The set of parameter names.
320 * @param root The function code block.
321 * @return The subset of parameters referenced after the first
322 * seen non-local side-effect.
323 */
324 private static Set<String> findParametersReferencedAfterSideEffect(
325 Set<String> parameters, Node root) {
326
327 // TODO(johnlenz): Consider using scope for this.
328 Set<String> locals = Sets.newHashSet(parameters);
329 gatherLocalNames(root, locals);
330
331 ReferencedAfterSideEffect collector = new ReferencedAfterSideEffect(
332 parameters, locals);
333 NodeUtil.visitPostOrder(
334 root,
335 collector,
336 collector);
337 return collector.getResults();
338 }
339
340 /**
341 * Collect parameter names referenced after a non-local side-effect.
342 *
343 * Assumptions:
344 * - We assume parameters are not modified in the function body
345 * (that is checked separately).
346 * - There are no inner functions (also checked separately).
347 *
348 * As we are trying to replace parameters with there passed in values
349 * we are interested in anything that may affect those value. So, ignoring
350 * changes to local variables, we look for things that may affect anything
351 * outside the local-state. Once such a side-effect is seen any following
352 * reference to the function parameters are collected. These will need
353 * to be assigned to temporaries to prevent changes to their value as would
354 * have happened during the function call.
355 *
356 * To properly handle loop structures all references to the function
357 * parameters are recorded and the decision to keep or throw away those
358 * references is deferred until exiting the loop structure.
359 */
360 private static class ReferencedAfterSideEffect
361 implements Visitor, Predicate<Node> {
362 private final Set<String> parameters;
363 private final Set<String> locals;
364 private boolean sideEffectSeen = false;
365 private Set<String> parametersReferenced = Sets.newHashSet();
366 private int loopsEntered = 0;
367
368 ReferencedAfterSideEffect(Set<String> parameters, Set<String> locals) {
369 this.parameters = parameters;
370 this.locals = locals;
371 }
372
373 Set<String> getResults() {
374 return parametersReferenced;
375 }
376
377 @Override
378 public boolean apply(Node node) {
379 // Keep track of any loop structures entered.
380 if (NodeUtil.isLoopStructure(node)) {
381 loopsEntered++;
382 }
383
384 // If we have found all the parameters, don't bother looking
385 // at the children.
386 return !(sideEffectSeen
387 && parameters.size() == parametersReferenced.size());
388 }
389
390 boolean inLoop() {
391 return loopsEntered != 0;
392 }
393
394 @Override
395 public void visit(Node n) {
396 // If we are exiting a loop.
397 if (NodeUtil.isLoopStructure(n)) {
398 loopsEntered--;
399 if (!inLoop() && !sideEffectSeen) {
400 // Now that the loops has been fully traversed and
401 // no side-effects have been seen, throw away
402 // the references seen in them.
403 parametersReferenced.clear();
404 }
405 }
406
407 if (!sideEffectSeen) {
408 // Look for side-effects.
409 if (hasNonLocalSideEffect(n)) {
410 sideEffectSeen = true;
411 }
412 }
413
414 // If traversing the nodes of a loop save any references
415 // that are seen.
416 if (inLoop() || sideEffectSeen) {
417 // Record references to parameters.
418 if (n.isName()) {
419 String name = n.getString();
420 if (parameters.contains(name)) {
421 parametersReferenced.add(name);
422 }
423 } else if (n.isThis()) {
424 parametersReferenced.add(THIS_MARKER);
425 }
426 }
427 }
428
429 /**
430 * @return Whether the node may have non-local side-effects.
431 */
432 private boolean hasNonLocalSideEffect(Node n) {
433 boolean sideEffect = false;
434 int type = n.getType();
435 // Note: Only care about changes to non-local names, specifically
436 // ignore VAR declaration assignments.
437 if (NodeUtil.isAssignmentOp(n)
438 || type == Token.INC
439 || type == Token.DEC) {
440 Node lhs = n.getFirstChild();
441 // Ignore changes to local names.
442 if (!isLocalName(lhs)) {
443 sideEffect = true;
444 }
445 } else if (type == Token.CALL) {
446 sideEffect = NodeUtil.functionCallHasSideEffects(n);
447 } else if (type == Token.NEW) {
448 sideEffect = NodeUtil.constructorCallHasSideEffects(n);
449 } else if (type == Token.DELPROP) {
450 sideEffect = true;
451 }
452
453 return sideEffect;
454 }
455
456 /**
457 * @return Whether node is a reference to locally declared name.
458 */
459 private boolean isLocalName(Node node) {
460 if (node.isName()) {
461 String name = node.getString();
462 return locals.contains(name);
463 }
464 return false;
465 }
466 }
467
468 /**
469 * Gather any names declared in the local scope.
470 */
471 private static void gatherLocalNames(Node n, Set<String> names) {
472 if (n.isFunction()) {
473 if (NodeUtil.isFunctionDeclaration(n)) {
474 names.add(n.getFirstChild().getString());
475 }
476 // Don't traverse into inner function scopes;
477 return;
478 } else if (n.isName()) {
479 switch (n.getParent().getType()) {
480 case Token.VAR:
481 case Token.CATCH:
482 names.add(n.getString());
483 }
484 }
485
486 for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
487 gatherLocalNames(c, names);
488 }
489 }
490
491 /**
492 * Get a set of function parameter names.
493 */
494 private static Set<String> getFunctionParameterSet(Node fnNode) {
495 Set<String> set = Sets.newHashSet();
496 for (Node n : NodeUtil.getFunctionParameters(fnNode).children()) {
497 set.add(n.getString());
498 }
499 return set;
500 }
501
502 }