Debian Codegraph @

src/com/google/javascript/jscomp/FunctionRewriter.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.collect.HashMultimap;
20 import com.google.common.collect.ImmutableList;
21 import com.google.common.collect.Multimap;
22 import com.google.javascript.jscomp.NodeTraversal.Callback;
23 import com.google.javascript.rhino.IR;
24 import com.google.javascript.rhino.Node;
25 import com.google.javascript.rhino.Token;
26
27 import java.util.Collection;
28 import java.util.List;
29
30 /**
31 * Reduces the size of common function expressions.
32 *
33 * This pass will rewrite:
34 *
35 * C.prototype.getA = function() { return this.a_ };
36 * C.prototype.setA = function(newValue) { this.a_ = newValue };
37 *
38 * as:
39 *
40 * C.prototype.getA = JSCompiler_get("a_);
41 * C.prototype.setA = JSCompiler_set("a_);
42 *
43 * if by doing so we will save bytes, after the helper functions are
44 * added and renaming is done.
45 *
46 */
47 class FunctionRewriter implements CompilerPass {
48 private final AbstractCompiler compiler;
49 // Safety margin used to avoid growing simple programs by a few bytes.
50 // Selected arbitrarily.
51 private static final int SAVINGS_THRESHOLD = 16;
52
53 FunctionRewriter(AbstractCompiler compiler) {
54 this.compiler = compiler;
55 }
56
57 @Override
58 public void process(Node externs, Node root) {
59 List<Reducer> reducers = ImmutableList.of(new ReturnConstantReducer(),
60 new GetterReducer(),
61 new SetterReducer(),
62 new EmptyFunctionReducer(),
63 new IdentityReducer());
64
65 Multimap<Reducer, Reduction> reductionMap = HashMultimap.create();
66
67 // Accumulate possible reductions in the reduction multi-map. They
68 // will be applied in the loop below.
69 NodeTraversal.traverse(compiler, root,
70 new ReductionGatherer(reducers, reductionMap));
71
72 // Apply reductions iff they will provide some savings.
73 for (Reducer reducer : reducers) {
74 Collection<Reduction> reductions = reductionMap.get(reducer);
75 if (reductions.isEmpty()) {
76 continue;
77 }
78
79 Node helperCode = parseHelperCode(reducer);
80 if (helperCode == null) {
81 continue;
82 }
83
84 int helperCodeCost = InlineCostEstimator.getCost(helperCode);
85
86 // Estimate savings
87 int savings = 0;
88 for (Reduction reduction : reductions) {
89 savings += reduction.estimateSavings();
90 }
91
92 // Compare estimated savings against the helper cost. Apply
93 // reductions if doing so will result in some savings.
94 if (savings > (helperCodeCost + SAVINGS_THRESHOLD)) {
95 for (Reduction reduction : reductions) {
96 reduction.apply();
97 }
98
99 Node addingRoot = compiler.getNodeForCodeInsertion(null);
100 addingRoot.addChildrenToFront(helperCode);
101 compiler.reportCodeChange();
102 }
103 }
104 }
105
106 /**
107 * Parse helper code needed by a reducer.
108 *
109 * @return Helper code root. If parse fails, return null.
110 */
111 public Node parseHelperCode(Reducer reducer) {
112 Node root = compiler.parseSyntheticCode(
113 reducer.getClass().toString() + ":helper", reducer.getHelperSource());
114 return (root != null) ? root.removeFirstChild() : null;
115 }
116
117 private static boolean isReduceableFunctionExpression(Node n) {
118 return NodeUtil.isFunctionExpression(n)
119 && !NodeUtil.isGetOrSetKey(n.getParent());
120 }
121
122 /**
123 * Information needed to apply a reduction.
124 */
125 private class Reduction {
126 private final Node parent;
127 private final Node oldChild;
128 private final Node newChild;
129
130 Reduction(Node parent, Node oldChild, Node newChild) {
131 this.parent = parent;
132 this.oldChild = oldChild;
133 this.newChild = newChild;
134 }
135
136 /**
137 * Apply the reduction by replacing the old child with the new child.
138 */
139 void apply() {
140 parent.replaceChild(oldChild, newChild);
141 compiler.reportCodeChange();
142 }
143
144 /**
145 * Estimate number of bytes saved by applying this reduction.
146 */
147 int estimateSavings() {
148 return InlineCostEstimator.getCost(oldChild) -
149 InlineCostEstimator.getCost(newChild);
150 }
151 }
152
153 /**
154 * Gathers a list of reductions to apply later by doing an in-order
155 * AST traversal. If a suitable reduction is found, stop traversal
156 * in that branch.
157 */
158 private class ReductionGatherer implements Callback {
159 private final List<Reducer> reducers;
160 private final Multimap<Reducer, Reduction> reductions;
161
162 /**
163 * @param reducers List of reducers to apply during traversal.
164 * @param reductions Reducer -> Reduction multimap,
165 * populated during traversal.
166 */
167 ReductionGatherer(List<Reducer> reducers,
168 Multimap<Reducer, Reduction> reductions) {
169 this.reducers = reducers;
170 this.reductions = reductions;
171 }
172
173 @Override
174 public boolean shouldTraverse(NodeTraversal raversal,
175 Node node,
176 Node parent) {
177 for (Reducer reducer : reducers) {
178 Node replacement = reducer.reduce(node);
179 if (replacement != node) {
180 reductions.put(reducer, new Reduction(parent, node, replacement));
181 return false;
182 }
183 }
184 return true;
185 }
186
187
188 @Override
189 public void visit(NodeTraversal traversal, Node node, Node parent) {
190 }
191 }
192
193 /**
194 * Interface implemented by the strength-reduction optimizers below.
195 */
196 abstract static class Reducer {
197 /**
198 * @return JS source for helper methods used by this reduction.
199 */
200 abstract String getHelperSource();
201
202 /**
203 * @return root of the reduced subtree if a reduction was applied;
204 * otherwise returns the node argument.
205 */
206 abstract Node reduce(Node node);
207
208 /**
209 * Builds a method call based on the the given method name,
210 * argument and history.
211 *
212 * @param methodName Method to call.
213 * @param argumentNode Method argument.
214 */
215 protected final Node buildCallNode(String methodName, Node argumentNode,
216 Node srcref) {
217 Node call = IR.call(IR.name(methodName)).srcref(srcref);
218 call.putBooleanProp(Node.FREE_CALL, true);
219 if (argumentNode != null) {
220 call.addChildToBack(argumentNode.cloneTree());
221 }
222 return call;
223 }
224 }
225
226 /**
227 * Reduces return immutable constant literal methods declarations
228 * with calls to a constant return method factory.
229 *
230 * Example:
231 * a.prototype.b = function() {}
232 * is reduced to:
233 * a.prototype.b = emptyFn();
234 */
235 private static class EmptyFunctionReducer extends Reducer {
236 static final String FACTORY_METHOD_NAME = "JSCompiler_emptyFn";
237 static final String HELPER_SOURCE =
238 "function " + FACTORY_METHOD_NAME + "() {" +
239 " return function() {}" +
240 "}";
241
242 @Override
243 public String getHelperSource() {
244 return HELPER_SOURCE;
245 }
246
247 @Override
248 public Node reduce(Node node) {
249 if (NodeUtil.isEmptyFunctionExpression(node)) {
250 return buildCallNode(FACTORY_METHOD_NAME, null, node);
251 } else {
252 return node;
253 }
254 }
255 }
256
257 /**
258 * Base class for reducers that match functions that contain a
259 * single return statement.
260 */
261 abstract static class SingleReturnStatementReducer extends Reducer {
262
263 /**
264 * @return function return value node if function body contains a
265 * single return statement. Otherwise, null.
266 */
267 protected final Node maybeGetSingleReturnRValue(Node functionNode) {
268 Node body = functionNode.getLastChild();
269 if (!body.hasOneChild()) {
270 return null;
271 }
272
273 Node statement = body.getFirstChild();
274 if (statement.isReturn()) {
275 return statement.getFirstChild();
276 }
277 return null;
278 }
279 }
280
281 /**
282 * Reduces property getter method declarations with calls to a
283 * getter method factory.
284 *
285 * Example:
286 * a.prototype.b = function(a) {return a}
287 * is reduced to:
288 * a.prototype.b = getter(a);
289 */
290 private static class IdentityReducer extends SingleReturnStatementReducer {
291 static final String FACTORY_METHOD_NAME = "JSCompiler_identityFn";
292 static final String HELPER_SOURCE =
293 "function " + FACTORY_METHOD_NAME + "() {" +
294 " return function(" + FACTORY_METHOD_NAME + "_value) {" +
295 "return " + FACTORY_METHOD_NAME + "_value}" +
296 "}";
297
298 @Override
299 public String getHelperSource() {
300 return HELPER_SOURCE;
301 }
302
303 @Override
304 public Node reduce(Node node) {
305 if (!isReduceableFunctionExpression(node)) {
306 return node;
307 }
308
309 if (isIdentityFunction(node)) {
310 return buildCallNode(FACTORY_METHOD_NAME, null, node);
311 } else {
312 return node;
313 }
314 }
315
316 /**
317 * Checks if the function matches the pattern:
318 * function(<value>, <rest>) {return <value>}
319 *
320 * @return Whether the function matches the pattern.
321 */
322 private boolean isIdentityFunction(Node functionNode) {
323 Node argList = functionNode.getFirstChild().getNext();
324 Node paramNode = argList.getFirstChild();
325 if (paramNode == null) {
326 return false;
327 }
328
329 Node value = maybeGetSingleReturnRValue(functionNode);
330 if (value != null &&
331 value.isName() &&
332 value.getString().equals(paramNode.getString())) {
333 return true;
334 }
335 return false;
336 }
337 }
338
339 /**
340 * Reduces return immutable constant literal methods declarations
341 * with calls to a constant return method factory.
342 *
343 * Example:
344 * a.prototype.b = function() {return 10}
345 * is reduced to:
346 * a.prototype.b = returnconst(10);
347 */
348 private static class ReturnConstantReducer
349 extends SingleReturnStatementReducer {
350 static final String FACTORY_METHOD_NAME = "JSCompiler_returnArg";
351 static final String HELPER_SOURCE =
352 "function " + FACTORY_METHOD_NAME +
353 "(" + FACTORY_METHOD_NAME + "_value) {" +
354 " return function() {return " + FACTORY_METHOD_NAME + "_value}" +
355 "}";
356
357 @Override
358 public String getHelperSource() {
359 return HELPER_SOURCE;
360 }
361
362 @Override
363 public Node reduce(Node node) {
364 if (!isReduceableFunctionExpression(node)) {
365 return node;
366 }
367
368 Node valueNode = getValueNode(node);
369 if (valueNode != null) {
370 return buildCallNode(FACTORY_METHOD_NAME, valueNode, node);
371 } else {
372 return node;
373 }
374 }
375
376 /**
377 * Checks if the function matches the pattern:
378 * function(<args>) {return <immutable value>}
379 * and returns <immutable value> if a match is found.
380 *
381 * @return the immutable value node; or null.
382 */
383 private Node getValueNode(Node functionNode) {
384 Node value = maybeGetSingleReturnRValue(functionNode);
385 if (value != null &&
386 NodeUtil.isImmutableValue(value)) {
387 return value;
388 }
389 return null;
390 }
391 }
392
393 /**
394 * Reduces property getter method declarations with calls to a
395 * getter method factory.
396 *
397 * Example:
398 * a.prototype.b = function() {return this.b_}
399 * is reduced to:
400 * a.prototype.b = getter("b_");
401 */
402 private static class GetterReducer extends SingleReturnStatementReducer {
403 static final String FACTORY_METHOD_NAME = "JSCompiler_get";
404 static final String HELPER_SOURCE =
405 "function " + FACTORY_METHOD_NAME + "(" +
406 FACTORY_METHOD_NAME + "_name) {" +
407 " return function() {return this[" + FACTORY_METHOD_NAME + "_name]}" +
408 "}";
409
410 @Override
411 public String getHelperSource() {
412 return HELPER_SOURCE;
413 }
414
415 @Override
416 public Node reduce(Node node) {
417 if (!isReduceableFunctionExpression(node)) {
418 return node;
419 }
420
421 Node propName = getGetPropertyName(node);
422 if (propName != null) {
423 if (!propName.isString()) {
424 throw new IllegalStateException(
425 "Expected STRING, got " + Token.name(propName.getType()));
426 }
427
428 return buildCallNode(FACTORY_METHOD_NAME, propName, node);
429 } else {
430 return node;
431 }
432 }
433
434 /**
435 * Checks if the function matches the pattern:
436 * function(<args>) {return this.<name>}
437 * and returns <name> if a match is found.
438 *
439 * @return STRING node that is the RHS of a this property get; or null.
440 */
441 private Node getGetPropertyName(Node functionNode) {
442 Node value = maybeGetSingleReturnRValue(functionNode);
443 if (value != null &&
444 value.isGetProp() &&
445 value.getFirstChild().isThis()) {
446 return value.getLastChild();
447 }
448 return null;
449 }
450 }
451
452 /**
453 * Reduces property setter method declarations with calls to a
454 * setter method factory.
455 *
456 * Example:
457 * a.prototype.setB = function(value) {this.b_ = value}
458 * reduces to:
459 * a.prototype.setB = getter("b_");
460 */
461 private static class SetterReducer extends Reducer {
462 static final String FACTORY_METHOD_NAME = "JSCompiler_set";
463 static final String HELPER_SOURCE =
464 "function " + FACTORY_METHOD_NAME + "(" +
465 FACTORY_METHOD_NAME + "_name) {" +
466 " return function(" + FACTORY_METHOD_NAME + "_value) {" +
467 "this[" + FACTORY_METHOD_NAME + "_name] = " +
468 FACTORY_METHOD_NAME + "_value}" +
469 "}";
470
471 @Override
472 public String getHelperSource() {
473 return HELPER_SOURCE;
474 }
475
476 @Override
477 public Node reduce(Node node) {
478 if (!isReduceableFunctionExpression(node)) {
479 return node;
480 }
481
482 Node propName = getSetPropertyName(node);
483 if (propName != null) {
484 if (!propName.isString()) {
485 throw new IllegalStateException(
486 "Expected STRING, got " + Token.name(propName.getType()));
487 }
488
489 return buildCallNode(FACTORY_METHOD_NAME, propName, node);
490 } else {
491 return node;
492 }
493 }
494
495 /**
496 * Checks if the function matches the pattern:
497 * function(<value>, <rest>) {this.<name> = <value>}
498 * and returns <name> if a match is found.
499 *
500 * @return STRING node that is the RHS of a this property get; or null.
501 */
502 private Node getSetPropertyName(Node functionNode) {
503 Node body = functionNode.getLastChild();
504 if (!body.hasOneChild()) {
505 return null;
506 }
507
508 Node argList = functionNode.getFirstChild().getNext();
509 Node paramNode = argList.getFirstChild();
510 if (paramNode == null) {
511 return null;
512 }
513
514 Node statement = body.getFirstChild();
515 if (!NodeUtil.isExprAssign(statement)) {
516 return null;
517 }
518
519 Node assign = statement.getFirstChild();
520 Node lhs = assign.getFirstChild();
521 if (lhs.isGetProp() && lhs.getFirstChild().isThis()) {
522 Node rhs = assign.getLastChild();
523 if (rhs.isName() &&
524 rhs.getString().equals(paramNode.getString())) {
525 Node propertyName = lhs.getLastChild();
526 return propertyName;
527 }
528 }
529 return null;
530 }
531 }
532 }