Debian Codegraph @

src/com/google/javascript/jscomp/FunctionToBlockMutator.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 static com.google.javascript.jscomp.FunctionArgumentInjector.THIS_MARKER;
19
20 import com.google.common.base.Preconditions;
21 import com.google.common.base.Supplier;
22 import com.google.common.collect.Lists;
23 import com.google.common.collect.Maps;
24 import com.google.javascript.jscomp.MakeDeclaredNamesUnique.InlineRenamer;
25 import com.google.javascript.rhino.IR;
26 import com.google.javascript.rhino.Node;
27 import com.google.javascript.rhino.Token;
28
29 import java.util.LinkedHashMap;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Map.Entry;
33 import java.util.Set;
34
35 /**
36 * A class to transform the body of a function into a generic block suitable
37 * for inlining.
38 *
39 * @author [email protected] (John Lenz)
40 */
41 class FunctionToBlockMutator {
42
43 private AbstractCompiler compiler;
44 private Supplier<String> safeNameIdSupplier;
45
46
47 FunctionToBlockMutator(
48 AbstractCompiler compiler, Supplier<String> safeNameIdSupplier) {
49 this.compiler = compiler;
50 this.safeNameIdSupplier = safeNameIdSupplier;
51 }
52
53 /**
54 * @param fnName The name to use when preparing human readable names.
55 * @param fnNode The function to prepare.
56 * @param callNode The call node that will be replaced.
57 * @param resultName Function results should be assigned to this name.
58 * @param needsDefaultResult Whether the result value must be set.
59 * @param isCallInLoop Whether the function body must be prepared to be
60 * injected into the body of a loop.
61 * @return A clone of the function body mutated to be suitable for injection
62 * as a statement into another code block.
63 */
64 Node mutate(String fnName, Node fnNode, Node callNode,
65 String resultName, boolean needsDefaultResult, boolean isCallInLoop) {
66 Node newFnNode = fnNode.cloneTree();
67 // Now that parameter names have been replaced, make sure all the local
68 // names are unique, to allow functions to be inlined multiple times
69 // without causing conflicts.
70 makeLocalNamesUnique(newFnNode, isCallInLoop);
71
72 // Function declarations must be rewritten as function expressions as
73 // they will be within a block and normalization prevents function
74 // declarations within block as browser implementations vary.
75 rewriteFunctionDeclarations(newFnNode.getLastChild());
76
77 // TODO(johnlenz): Mark NAME nodes constant for parameters that are not
78 // modified.
79 Set<String> namesToAlias =
80 FunctionArgumentInjector.findModifiedParameters(newFnNode);
81 LinkedHashMap<String, Node> args =
82 FunctionArgumentInjector.getFunctionCallParameterMap(
83 newFnNode, callNode, this.safeNameIdSupplier);
84 boolean hasArgs = !args.isEmpty();
85 if (hasArgs) {
86 FunctionArgumentInjector.maybeAddTempsForCallArguments(
87 newFnNode, args, namesToAlias, compiler.getCodingConvention());
88 }
89
90 Node newBlock = NodeUtil.getFunctionBody(newFnNode);
91 // Make the newBlock insertable .
92 newBlock.detachFromParent();
93
94 if (hasArgs) {
95 Node inlineResult = aliasAndInlineArguments(newBlock,
96 args, namesToAlias);
97 Preconditions.checkState(newBlock == inlineResult);
98 }
99
100 //
101 // For calls inlined into loops, VAR declarations are not reinitialized to
102 // undefined as they would have been if the function were called, so ensure
103 // that they are properly initialized.
104 //
105 if (isCallInLoop) {
106 fixUnitializedVarDeclarations(newBlock);
107 }
108
109 String labelName = getLabelNameForFunction(fnName);
110 Node injectableBlock = replaceReturns(
111 newBlock, resultName, labelName, needsDefaultResult);
112 Preconditions.checkState(injectableBlock != null);
113
114 return injectableBlock;
115 }
116
117
118 /**
119 * @param n The node to inspect
120 */
121 private void rewriteFunctionDeclarations(Node n) {
122 if (n.isFunction()) {
123 if (NodeUtil.isFunctionDeclaration(n)) {
124 // Rewrite: function f() {} ==> var f = function() {}
125 Node fnNameNode = n.getFirstChild();
126
127 Node name = IR.name(fnNameNode.getString()).srcref(fnNameNode);
128 Node var = IR.var(name).srcref(n);
129
130 fnNameNode.setString("");
131 // Add the VAR, remove the FUNCTION
132 n.getParent().replaceChild(n, var);
133 // readd the function as a function expression
134 name.addChildToFront(n);
135 }
136 return;
137 }
138
139 for (Node c = n.getFirstChild(), next; c != null; c = next) {
140 next = c.getNext(); // We may rewrite "c"
141 rewriteFunctionDeclarations(c);
142 }
143 }
144
145 /**
146 * For all VAR node with uninitialized declarations, set
147 * the values to be "undefined".
148 */
149 private void fixUnitializedVarDeclarations(Node n) {
150 // Inner loop structure must already have logic to initialize its
151 // variables. In particular FOR-IN structures must not be modified.
152 if (NodeUtil.isLoopStructure(n)) {
153 return;
154 }
155
156 // For all VARs
157 if (n.isVar()) {
158 Node name = n.getFirstChild();
159 // It isn't initialized.
160 if (!name.hasChildren()) {
161 Node srcLocation = name;
162 name.addChildToBack(NodeUtil.newUndefinedNode(srcLocation));
163 }
164 return;
165 }
166
167 for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
168 fixUnitializedVarDeclarations(c);
169 }
170 }
171
172
173 /**
174 * Fix-up all local names to be unique for this subtree.
175 * @param fnNode A mutable instance of the function to be inlined.
176 */
177 private void makeLocalNamesUnique(Node fnNode, boolean isCallInLoop) {
178 Supplier<String> idSupplier = compiler.getUniqueNameIdSupplier();
179 // Make variable names unique to this instance.
180 NodeTraversal.traverse(
181 compiler, fnNode, new MakeDeclaredNamesUnique(
182 new InlineRenamer(
183 compiler.getCodingConvention(),
184 idSupplier,
185 "inline_",
186 isCallInLoop)));
187 // Make label names unique to this instance.
188 new RenameLabels(compiler, new LabelNameSupplier(idSupplier), false)
189 .process(null, fnNode);
190 }
191
192 static class LabelNameSupplier implements Supplier<String> {
193 final Supplier<String> idSupplier;
194
195 LabelNameSupplier(Supplier<String> idSupplier) {
196 this.idSupplier = idSupplier;
197 }
198
199 @Override
200 public String get() {
201 return "JSCompiler_inline_label_" + idSupplier.get();
202 }
203 }
204
205 /**
206 * Create a unique label name.
207 */
208 private String getLabelNameForFunction(String fnName){
209 String name = (fnName == null || fnName.isEmpty()) ? "anon" : fnName;
210 return "JSCompiler_inline_label_" + name + "_" + safeNameIdSupplier.get();
211 }
212
213 /**
214 * Create a unique "this" name.
215 */
216 private String getUniqueThisName() {
217 return "JSCompiler_inline_this_" + safeNameIdSupplier.get();
218 }
219
220 /**
221 * Inlines the arguments within the node tree using the given argument map,
222 * replaces "unsafe" names with local aliases.
223 *
224 * The aliases for unsafe require new VAR declarations, so this function
225 * can not be used in for direct CALL node replacement as VAR nodes can not be
226 * created there.
227 *
228 * @return The node or its replacement.
229 */
230 private Node aliasAndInlineArguments(
231 Node fnTemplateRoot, LinkedHashMap<String, Node> argMap,
232 Set<String> namesToAlias) {
233
234 if (namesToAlias == null || namesToAlias.isEmpty()) {
235 // There are no names to alias, just inline the arguments directly.
236 Node result = FunctionArgumentInjector.inject(
237 compiler, fnTemplateRoot, null, argMap);
238 Preconditions.checkState(result == fnTemplateRoot);
239 return result;
240 } else {
241 // Create local alias of names that can not be safely
242 // used directly.
243
244 // An arg map that will be updated to contain the
245 // safe aliases.
246 Map<String, Node> newArgMap = Maps.newHashMap(argMap);
247
248 // Declare the alias in the same order as they
249 // are declared.
250 List<Node> newVars = Lists.newLinkedList();
251 // NOTE: argMap is a linked map so we get the parameters in the
252 // order that they were declared.
253 for (Entry<String, Node> entry : argMap.entrySet()) {
254 String name = entry.getKey();
255 if (namesToAlias.contains(name)) {
256 if (name.equals(THIS_MARKER)) {
257 boolean referencesThis = NodeUtil.referencesThis(fnTemplateRoot);
258 // Update "this", this is only necessary if "this" is referenced
259 // and the value of "this" is not Token.THIS, or the value of "this"
260 // has side effects.
261
262 Node value = entry.getValue();
263 if (!value.isThis()
264 && (referencesThis
265 || NodeUtil.mayHaveSideEffects(value, compiler))) {
266 String newName = getUniqueThisName();
267 Node newValue = entry.getValue().cloneTree();
268 Node newNode = NodeUtil.newVarNode(newName, newValue)
269 .copyInformationFromForTree(newValue);
270 newVars.add(0, newNode);
271 // Remove the parameter from the list to replace.
272 newArgMap.put(THIS_MARKER,
273 IR.name(newName)
274 .srcrefTree(newValue));
275 }
276 } else {
277 Node newValue = entry.getValue().cloneTree();
278 Node newNode = NodeUtil.newVarNode(name, newValue)
279 .copyInformationFromForTree(newValue);
280 newVars.add(0, newNode);
281 // Remove the parameter from the list to replace.
282 newArgMap.remove(name);
283 }
284 }
285 }
286
287 // Inline the arguments.
288 Node result = FunctionArgumentInjector.inject(
289 compiler, fnTemplateRoot, null, newArgMap);
290 Preconditions.checkState(result == fnTemplateRoot);
291
292 // Now that the names have been replaced, add the new aliases for
293 // the old names.
294 for (Node n : newVars) {
295 fnTemplateRoot.addChildToFront(n);
296 }
297
298 return result;
299 }
300 }
301
302 /**
303 * Convert returns to assignments and breaks, as needed.
304 * For example, with a labelName of 'foo':
305 * {
306 * return a;
307 * }
308 * becomes:
309 * foo: {
310 * a;
311 * break foo;
312 * }
313 * or
314 * foo: {
315 * resultName = a;
316 * break foo;
317 * }
318 *
319 * @param resultMustBeSet Whether the result must always be set to a value.
320 * @return The node containing the transformed block, this may be different
321 * than the passed in node 'block'.
322 */
323 private static Node replaceReturns(
324 Node block, String resultName, String labelName,
325 boolean resultMustBeSet) {
326 Preconditions.checkNotNull(block);
327 Preconditions.checkNotNull(labelName);
328
329 Node root = block;
330
331 boolean hasReturnAtExit = false;
332 int returnCount = NodeUtil.getNodeTypeReferenceCount(
333 block, Token.RETURN, new NodeUtil.MatchShallowStatement());
334 if (returnCount > 0) {
335 hasReturnAtExit = hasReturnAtExit(block);
336 // TODO(johnlenz): Simpler not to special case this,
337 // and let it be optimized later.
338 if (hasReturnAtExit) {
339 convertLastReturnToStatement(block, resultName);
340 returnCount--;
341 }
342
343 if (returnCount > 0) {
344 // A label and breaks are needed.
345
346 // Add the breaks
347 replaceReturnWithBreak(block, null, resultName, labelName);
348
349 // Add label
350 Node name = IR.labelName(labelName).srcref(block);
351 Node label = IR.label(name, block).srcref(block);
352
353 Node newRoot = IR.block().srcref(block);
354 newRoot.addChildrenToBack(label);
355
356
357 // The label is now the root.
358 root = newRoot;
359 }
360 }
361
362 // If there wasn't an return at the end of the function block, and we need
363 // a result, add one to the block.
364 if (resultMustBeSet && !hasReturnAtExit && resultName != null) {
365 addDummyAssignment(block, resultName);
366 }
367
368 return root;
369 }
370
371 /**********************************************************************
372 * Functions following here are general node transformation functions
373 **********************************************************************/
374
375 /**
376 * Example:
377 * a = (void) 0;
378 */
379 private static void addDummyAssignment(Node node, String resultName) {
380 Preconditions.checkArgument(node.isBlock());
381
382 // A result is needed create a dummy value.
383 Node srcLocation = node;
384 Node retVal = NodeUtil.newUndefinedNode(srcLocation);
385 Node resultNode = createAssignStatementNode(resultName, retVal);
386 resultNode.copyInformationFromForTree(node);
387
388 node.addChildrenToBack(resultNode);
389 }
390
391 /**
392 * Replace the 'return' statement with its child expression.
393 * "return foo()" becomes "foo()" or "resultName = foo()"
394 * "return" is removed or becomes "resultName = void 0".
395 *
396 * @param block
397 * @param resultName
398 */
399 private static void convertLastReturnToStatement(
400 Node block, String resultName) {
401 Node ret = block.getLastChild();
402 Preconditions.checkArgument(ret.isReturn());
403 Node resultNode = getReplacementReturnStatement(ret, resultName);
404
405 if (resultNode == null) {
406 block.removeChild(ret);
407 } else {
408 resultNode.copyInformationFromForTree(ret);
409 block.replaceChild(ret, resultNode);
410 }
411 }
412
413 /**
414 * Create a valid statement Node containing an assignment to name of the
415 * given expression.
416 */
417 private static Node createAssignStatementNode(String name, Node expression) {
418 // Create 'name = result-expression;' statement.
419 // EXPR (ASSIGN (NAME, EXPRESSION))
420 Node nameNode = IR.name(name);
421 Node assign = IR.assign(nameNode, expression);
422 return NodeUtil.newExpr(assign);
423 }
424
425 /**
426 * Replace the 'return' statement with its child expression.
427 * If the result is needed (resultName != null):
428 * "return foo()" becomes "resultName = foo()"
429 * "return" becomes "resultName = void 0".
430 * Otherwise:
431 * "return foo()" becomes "foo()"
432 * "return", null is returned.
433 */
434 private static Node getReplacementReturnStatement(
435 Node node, String resultName) {
436 Node resultNode = null;
437
438 Node retVal = null;
439 if (node.hasChildren()) {
440 // Clone the child as the child hasn't been removed
441 // from the node yet.
442 retVal = node.getFirstChild().cloneTree();
443 }
444
445 if (resultName == null) {
446 if (retVal != null) {
447 resultNode = NodeUtil.newExpr(retVal); // maybe null.
448 }
449 } else {
450 if (retVal == null) {
451 // A result is needed create a dummy value.
452 Node srcLocation = node;
453 retVal = NodeUtil.newUndefinedNode(srcLocation);
454 }
455 // Create a "resultName = retVal;" statement.
456 resultNode = createAssignStatementNode(resultName, retVal);
457 }
458
459 return resultNode;
460 }
461
462 /**
463 * @return Whether the given block end with an return statement.
464 */
465 private static boolean hasReturnAtExit(Node block) {
466 // Only inline functions that return something (empty returns
467 // will be handled by ConstFolding+EmptyFunctionRemoval)
468 return (block.getLastChild().isReturn());
469 }
470
471 /**
472 * Replace the 'return' statement with its child expression.
473 * "return foo()" becomes "{foo(); break;}" or
474 * "{resultName = foo(); break;}"
475 * "return" becomes {break;} or "{resultName = void 0;break;}".
476 */
477 private static Node replaceReturnWithBreak(Node current, Node parent,
478 String resultName, String labelName) {
479
480 if (current.isFunction()
481 || current.isExprResult()) {
482 // Don't recurse into functions definitions, and expressions can't
483 // contain RETURN nodes.
484 return current;
485 }
486
487 if (current.isReturn()) {
488 Preconditions.checkState(NodeUtil.isStatementBlock(parent));
489
490 Node resultNode = getReplacementReturnStatement(current, resultName);
491 Node breakNode = IR.breakNode(IR.labelName(labelName));
492
493 // Replace the node in parent, and reset current to the first new child.
494 breakNode.copyInformationFromForTree(current);
495 parent.replaceChild(current, breakNode);
496 if (resultNode != null) {
497 resultNode.copyInformationFromForTree(current);
498 parent.addChildBefore(resultNode, breakNode);
499 }
500 current = breakNode;
501 } else {
502 for (Node c = current.getFirstChild(); c != null; c = c.getNext()) {
503 // c may be replaced.
504 c = replaceReturnWithBreak(c, current, resultName, labelName);
505 }
506 }
507
508 return current;
509 }
510 }