Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2007 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.Lists;
20 import com.google.javascript.jscomp.NodeTraversal.Callback;
21 import com.google.javascript.rhino.IR;
22 import com.google.javascript.rhino.Node;
23 import java.util.Collection;
24 import java.util.List;
25 import java.util.logging.Logger;
26
27 /**
28 * Inlines methods that take no arguments and have only a return statement
29 * returning a property. Because it works on method names rather than type
30 * inference, a method with multiple definitions will be inlined if each
31 * definition is identical.
32 *
33 * <pre>
34 * A.prototype.foo = function() { return this.b; }
35 * B.prototype.foo = function() { return this.b; }
36 * </pre>
37 *
38 * will inline foo, but
39 *
40 * <pre>
41 * A.prototype.foo = function() { return this.b; }
42 * B.prototype.foo = function() { return this.c; }
43 * </pre>
44 *
45 * will not.
46 *
47 * Declarations are not removed because we do not find all possible
48 * call sites. For examples, calls of the form foo["bar"] are not
49 * detected.
50 *
51 */
52 class InlineSimpleMethods extends MethodCompilerPass {
53
54 private static final Logger logger =
55 Logger.getLogger(InlineSimpleMethods.class.getName());
56
57 InlineSimpleMethods(AbstractCompiler compiler) {
58 super(compiler);
59 }
60
61 /**
62 * For each method call, see if it is a candidate for inlining.
63 * TODO(kushal): Cache the results of the checks
64 */
65 private class InlineTrivialAccessors extends InvocationsCallback {
66
67 @Override
68 void visit(NodeTraversal t, Node callNode, Node parent, String callName) {
69 if (externMethods.contains(callName) ||
70 nonMethodProperties.contains(callName)) {
71 return;
72 }
73
74 Collection<Node> definitions = methodDefinitions.get(callName);
75 if (definitions == null || definitions.size() == 0) {
76 return;
77 }
78
79 // Do check of arity, complexity, and consistency in what we think is
80 // the order from least to most complex
81 Node firstDefinition = definitions.iterator().next();
82
83 // Check any multiple definitions
84 if (definitions.size() == 1 || allDefinitionsEquivalent(definitions)) {
85
86 if (!argsMayHaveSideEffects(callNode)) {
87 // Verify this is a trivial return
88 Node returned = returnedExpression(firstDefinition);
89 if (returned != null) {
90 if (isPropertyTree(returned)) {
91 logger.fine("Inlining property accessor: " + callName);
92 inlinePropertyReturn(parent, callNode, returned);
93 } else if (NodeUtil.isLiteralValue(returned, false) &&
94 !NodeUtil.mayHaveSideEffects(
95 callNode.getFirstChild(), compiler)) {
96 logger.fine("Inlining constant accessor: " + callName);
97 inlineConstReturn(parent, callNode, returned);
98 }
99 } else if (isEmptyMethod(firstDefinition) &&
100 !NodeUtil.mayHaveSideEffects(
101 callNode.getFirstChild(), compiler)) {
102 logger.fine("Inlining empty method: " + callName);
103 inlineEmptyMethod(parent, callNode);
104 }
105 }
106 } else {
107 logger.fine("Method '" + callName + "' has conflicting definitions.");
108 }
109 }
110 }
111
112 @Override
113 Callback getActingCallback() {
114 return new InlineTrivialAccessors();
115 }
116
117 /**
118 * Returns true if the provided node is a getprop for
119 * which the left child is this or a valid property tree
120 * and for which the right side is a string.
121 */
122 private static boolean isPropertyTree(Node expectedGetprop) {
123 if (!expectedGetprop.isGetProp()) {
124 return false;
125 }
126
127 Node leftChild = expectedGetprop.getFirstChild();
128 if (!leftChild.isThis() &&
129 !isPropertyTree(leftChild)) {
130 return false;
131 }
132
133 Node retVal = leftChild.getNext();
134 if (NodeUtil.getStringValue(retVal) == null) {
135 return false;
136 }
137 return true;
138 }
139
140 /**
141 * Finds the occurrence of "this" in the provided property tree and replaces
142 * it with replacement
143 */
144 private static void replaceThis(Node expectedGetprop, Node replacement) {
145 Node leftChild = expectedGetprop.getFirstChild();
146 if (leftChild.isThis()) {
147 expectedGetprop.replaceChild(leftChild, replacement);
148 } else {
149 replaceThis(leftChild, replacement);
150 }
151 }
152
153 /**
154 * Return the node that represents the expression returned
155 * by the method, given a FUNCTION node.
156 */
157 private static Node returnedExpression(Node fn) {
158 Node expectedBlock = getMethodBlock(fn);
159 if (!expectedBlock.hasOneChild()) {
160 return null;
161 }
162
163 Node expectedReturn = expectedBlock.getFirstChild();
164 if (!expectedReturn.isReturn()) {
165 return null;
166 }
167
168 if (!expectedReturn.hasOneChild()) {
169 return null;
170 }
171
172 return expectedReturn.getLastChild();
173 }
174
175
176 /**
177 * Return whether the given FUNCTION node is an empty method definition.
178 *
179 * Must be private, or moved to NodeUtil.
180 */
181 private static boolean isEmptyMethod(Node fn) {
182 Node expectedBlock = getMethodBlock(fn);
183 return expectedBlock == null ?
184 false : NodeUtil.isEmptyBlock(expectedBlock);
185 }
186
187 /**
188 * Return a BLOCK node if the given FUNCTION node is a valid method
189 * definition, null otherwise.
190 *
191 * Must be private, or moved to NodeUtil.
192 */
193 private static Node getMethodBlock(Node fn) {
194 if (fn.getChildCount() != 3) {
195 return null;
196 }
197
198 Node expectedBlock = fn.getLastChild();
199 return expectedBlock.isBlock() ?
200 expectedBlock : null;
201 }
202
203 /**
204 * Given a set of method definitions, verify they are the same.
205 */
206 private boolean allDefinitionsEquivalent(
207 Collection<Node> definitions) {
208 List<Node> list = Lists.newArrayList();
209 list.addAll(definitions);
210 Node node0 = list.get(0);
211 for (int i = 1; i < list.size(); i++) {
212 if (!compiler.areNodesEqualForInlining(list.get(i), node0)) {
213 return false;
214 }
215 }
216 return true;
217 }
218
219 /**
220 * Replace the provided method call with the tree specified in returnedValue
221 *
222 * Parse tree of a call is
223 * name
224 * call
225 * getprop
226 * obj
227 * string
228 */
229 private void inlinePropertyReturn(Node parent, Node call,
230 Node returnedValue) {
231 Node getProp = returnedValue.cloneTree();
232 replaceThis(getProp, call.getFirstChild().removeFirstChild());
233 parent.replaceChild(call, getProp);
234 compiler.reportCodeChange();
235 }
236
237 /**
238 * Replace the provided object and its method call with the tree specified
239 * in returnedValue. Should be called only if the object reference has
240 * no side effects.
241 */
242 private void inlineConstReturn(Node parent, Node call,
243 Node returnedValue) {
244 Node retValue = returnedValue.cloneTree();
245 parent.replaceChild(call, retValue);
246 compiler.reportCodeChange();
247 }
248
249 /**
250 * Remove the provided object and its method call.
251 */
252 private void inlineEmptyMethod(Node parent, Node call) {
253 // If the return value of the method call is read,
254 // replace it with "void 0". Otherwise, remove the call entirely.
255 if (NodeUtil.isExprCall(parent)) {
256 parent.getParent().replaceChild(parent, IR.empty());
257 } else {
258 Node srcLocation = call;
259 parent.replaceChild(call, NodeUtil.newUndefinedNode(srcLocation));
260 }
261 compiler.reportCodeChange();
262 }
263
264 /**
265 * Check whether the given method call's arguments have side effects.
266 * @param call The call node of a method invocation.
267 */
268 private boolean argsMayHaveSideEffects(Node call) {
269 for (Node currentChild = call.getFirstChild().getNext();
270 currentChild != null;
271 currentChild = currentChild.getNext()) {
272 if (NodeUtil.mayHaveSideEffects(currentChild, compiler)) {
273 return true;
274 }
275 }
276
277 return false;
278 }
279
280 /**
281 * A do-nothing signature store.
282 */
283 static final MethodCompilerPass.SignatureStore DUMMY_SIGNATURE_STORE =
284 new MethodCompilerPass.SignatureStore() {
285 @Override
286 public void addSignature(
287 String functionName, Node functionNode, String sourceFile) {
288 }
289
290 @Override
291 public void removeSignature(String functionName) {
292 }
293
294 @Override
295 public void reset() {
296 }
297 };
298
299 @Override
300 SignatureStore getSignatureStore() {
301 return DUMMY_SIGNATURE_STORE;
302 }
303 }