Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2008 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.AbstractShallowCallback;
21 import com.google.javascript.rhino.IR;
22 import com.google.javascript.rhino.Node;
23 import java.util.LinkedList;
24 import java.util.List;
25
26 /**
27 * When there are multiple prototype member declarations to the same class,
28 * use a temp variable to alias the prototype object.
29 *
30 * Example:
31 *
32 * <pre>
33 * function B() { ... } \
34 * B.prototype.foo = function() { ... } \___ {@link ExtractionInstance}
35 * ... /
36 * B.prototype.bar = function() { ... } /
37 * ^---------------------------------{@link PrototypeMemberDeclaration}
38 * </pre>
39 * <p>becomes
40 * <pre>
41 * function B() { ... }
42 * x = B.prototype;
43 * x.foo = function() { ... }
44 * ...
45 * x.bar = function() { ... }
46 * </pre>
47 *
48 * <p> Works almost like a redundant load elimination but limited to only
49 * recognizing the class prototype declaration idiom. First it only works within
50 * a basic block because we avoided {@link DataFlowAnalysis} for compilation
51 * performance. Secondly, we can avoid having to compute how long to
52 * sub-expressing has to be. Example:
53 * <pre>
54 * a.b.c.d = ...
55 * a.b.c = ...
56 * a.b = ...
57 * a.b.c = ...
58 * </pre>
59 * <p> Further more, we only introduce one temp variable to hold a single
60 * prototype at a time. So all the {@link PrototypeMemberDeclaration}
61 * to be extracted must be in a single line. We call this a single
62 * {@link ExtractionInstance}.
63 *
64 * <p>Alternatively, for users who do not want a global variable to be
65 * introduced, we will create an anonymous function instead.
66 * <pre>
67 * function B() { ... }
68 * (function (x) {
69 * x.foo = function() { ... }
70 * ...
71 * x.bar = function() { ... }
72 * )(B.prototype)
73 * </pre>
74 *
75 * The RHS of the declarations can have side effects, however, one good way to
76 * break this is the following:
77 * <pre>
78 * function B() { ... }
79 * B.prototype.foo = (function() { B.prototype = somethingElse(); return 0 })();
80 * ...
81 * </pre>
82 * Such logic is highly unlikely and we will assume that it never occurs.
83 *
84 */
85 class ExtractPrototypeMemberDeclarations implements CompilerPass {
86
87 // The name of variable that will temporary hold the pointer to the prototype
88 // object. Of cause, we assume that it'll be renamed by RenameVars.
89 private String prototypeAlias = "JSCompiler_prototypeAlias";
90
91 private final AbstractCompiler compiler;
92
93 private final Pattern pattern;
94
95 enum Pattern {
96 USE_GLOBAL_TEMP(
97 // Global Overhead.
98 // We need a temp variable to hold all the prototype.
99 "var t;".length(),
100 // Per Extract overhead:
101 // Every extraction instance must first use the temp variable to point
102 // to the prototype object.
103 "t=y.prototype;".length(),
104 // TODO(user): Check to to see if AliasExterns is on
105 // The gain we get per prototype declaration. Assuming it can be
106 // aliased.
107 "t.y=".length() - "x[p].y=".length()),
108
109 USE_ANON_FUNCTION(
110 // Global Overhead:
111 0,
112 // Per-extraction overhead:
113 // This is the cost of a single anoynmous function.
114 "(function(t){})(y.prototype);".length(),
115 // Per-prototype member declaration overhead:
116 // Here we assumes that they don't have AliasExterns on (in SIMPLE mode).
117 "t.y=".length() - "x.prototype.y=".length());
118
119
120 private final int globalOverhead;
121 private final int perExtractionOverhead;
122 private final int perMemberOverhead;
123
124 Pattern(int globalOverHead, int perExtractionOverhead, int perMemberOverhead) {
125 this.globalOverhead = globalOverHead;
126 this.perExtractionOverhead = perExtractionOverhead;
127 this.perMemberOverhead = perMemberOverhead;
128 }
129 }
130
131 ExtractPrototypeMemberDeclarations(AbstractCompiler compiler, Pattern pattern) {
132 this.compiler = compiler;
133 this.pattern = pattern;
134 }
135
136 @Override
137 public void process(Node externs, Node root) {
138 GatherExtractionInfo extractionInfo = new GatherExtractionInfo();
139 NodeTraversal.traverse(compiler, root, extractionInfo);
140 if (extractionInfo.shouldExtract()) {
141 doExtraction(extractionInfo);
142 compiler.reportCodeChange();
143 }
144 }
145
146 /**
147 * Declares the temp variable to point to prototype objects and iterates
148 * through all ExtractInstance and performs extraction there.
149 */
150 private void doExtraction(GatherExtractionInfo info) {
151
152 // Insert a global temp if we are using the USE_GLOBAL_TEMP pattern.
153 if (pattern == Pattern.USE_GLOBAL_TEMP) {
154 Node injectionPoint = compiler.getNodeForCodeInsertion(null);
155
156 Node var = NodeUtil.newVarNode(prototypeAlias, null)
157 .copyInformationFromForTree(injectionPoint);
158
159 injectionPoint.addChildrenToFront(var);
160 }
161 // Go through all extraction instances and extract each of them.
162 for (ExtractionInstance instance : info.instances) {
163 extractInstance(instance);
164 }
165 }
166
167 /**
168 * At a given ExtractionInstance, stores and prototype object in the temp
169 * variable and rewrite each member declaration to assign to the temp variable
170 * instead.
171 */
172 private void extractInstance(ExtractionInstance instance) {
173 PrototypeMemberDeclaration first = instance.declarations.getFirst();
174 String className = first.qualifiedClassName;
175 if (pattern == Pattern.USE_GLOBAL_TEMP) {
176 // Use the temp variable to hold the prototype.
177 Node stmt = new Node(first.node.getType(),
178 IR.assign(
179 IR.name(prototypeAlias),
180 NodeUtil.newQualifiedNameNode(
181 compiler.getCodingConvention(), className + ".prototype",
182 instance.parent, className + ".prototype")))
183 .copyInformationFromForTree(first.node);
184
185 instance.parent.addChildBefore(stmt, first.node);
186 } else if (pattern == Pattern.USE_ANON_FUNCTION){
187 Node block = IR.block();
188 Node func = IR.function(
189 IR.name(""),
190 IR.paramList(IR.name(prototypeAlias)),
191 block);
192
193 Node call = IR.call(func,
194 NodeUtil.newQualifiedNameNode(
195 compiler.getCodingConvention(), className + ".prototype",
196 instance.parent, className + ".prototype"));
197 call.putIntProp(Node.FREE_CALL, 1);
198
199 Node stmt = new Node(first.node.getType(), call);
200 stmt.copyInformationFromForTree(first.node);
201 instance.parent.addChildBefore(stmt, first.node);
202 for (PrototypeMemberDeclaration declar : instance.declarations) {
203 block.addChildToBack(declar.node.detachFromParent());
204 }
205 }
206 // Go thought each member declaration and replace it with an assignment
207 // to the prototype variable.
208 for (PrototypeMemberDeclaration declar : instance.declarations) {
209 replacePrototypeMemberDeclaration(declar);
210 }
211 }
212
213 /**
214 * Replaces a member declaration to an assignment to the temp prototype
215 * object.
216 */
217 private void replacePrototypeMemberDeclaration(
218 PrototypeMemberDeclaration declar) {
219 // x.prototype.y = ... -> t.y = ...
220 Node assignment = declar.node.getFirstChild();
221 Node lhs = assignment.getFirstChild();
222 Node name = NodeUtil.newQualifiedNameNode(
223 compiler.getCodingConvention(),
224 prototypeAlias + "." + declar.memberName, declar.node,
225 declar.memberName);
226
227 // Save the full prototype path on the left hand side of the assignment
228 // for debugging purposes.
229 // declar.lhs = x.prototype.y so first child of the first child
230 // is 'x'.
231 Node accessNode = declar.lhs.getFirstChild().getFirstChild();
232 Object originalName = accessNode.getProp(Node.ORIGINALNAME_PROP);
233
234 String className = "?";
235
236 if (originalName != null) {
237 className = originalName.toString();
238 }
239
240 NodeUtil.setDebugInformation(name.getFirstChild(), lhs,
241 className + ".prototype");
242
243 assignment.replaceChild(lhs, name);
244 }
245
246 /**
247 * Collects all the possible extraction instances in a node traversal.
248 */
249 private class GatherExtractionInfo extends AbstractShallowCallback {
250
251 private List<ExtractionInstance> instances = Lists.newLinkedList();
252 private int totalDelta = pattern.globalOverhead;
253
254 @Override
255 public void visit(NodeTraversal t, Node n, Node parent) {
256
257 if (!n.isScript() && !n.isBlock()) {
258 return;
259 }
260
261 for (Node cur = n.getFirstChild(); cur != null; cur = cur.getNext()) {
262 PrototypeMemberDeclaration prototypeMember =
263 PrototypeMemberDeclaration.extractDeclaration(cur);
264 if (prototypeMember == null) {
265 continue;
266 }
267
268 // Found a good site here. The constructor will computes the chain of
269 // declarations that is qualified for extraction.
270 ExtractionInstance instance =
271 new ExtractionInstance(prototypeMember, n);
272 cur = instance.declarations.getLast().node;
273
274 // Only add it to our work list if the extraction at this instance
275 // makes the code smaller.
276 if (instance.isFavorable()) {
277 instances.add(instance);
278 totalDelta += instance.delta;
279 }
280 }
281 }
282
283 /**
284 * @return <@code true> if the sum of all the extraction instance gain
285 * outweighs the overhead of the temp variable declaration.
286 */
287 private boolean shouldExtract() {
288 return totalDelta < 0;
289 }
290 }
291
292 private class ExtractionInstance {
293 LinkedList<PrototypeMemberDeclaration> declarations = Lists.newLinkedList();
294 private int delta = 0;
295 private final Node parent;
296
297 private ExtractionInstance(PrototypeMemberDeclaration head, Node parent) {
298 this.parent = parent;
299 declarations.add(head);
300 delta = pattern.perExtractionOverhead + pattern.perMemberOverhead;
301
302 for (Node cur = head.node.getNext(); cur != null; cur = cur.getNext()) {
303
304 // We can skip over any named functions because they have no effect on
305 // the control flow. In fact, they are lifted to the beginning of the
306 // block. This happens a lot when devirtualization breaks the whole
307 // chain.
308 if (cur.isFunction()) {
309 continue;
310 }
311
312 PrototypeMemberDeclaration prototypeMember =
313 PrototypeMemberDeclaration.extractDeclaration(cur);
314 if (prototypeMember == null || !head.isSameClass(prototypeMember)) {
315 break;
316 }
317 declarations.add(prototypeMember);
318 delta += pattern.perMemberOverhead;
319 }
320 }
321
322 /**
323 * @return {@code true} if extracting all the declarations at this instance
324 * will overweight the overhead of aliasing the prototype object.
325 */
326 boolean isFavorable() {
327 return delta <= 0;
328 }
329 }
330
331 /**
332 * Abstraction for a prototype member declaration.
333 *
334 * <p>{@code a.b.c.prototype.d = ....}
335 */
336 private static class PrototypeMemberDeclaration {
337 final String memberName;
338 final Node node;
339 final String qualifiedClassName;
340 final Node lhs;
341
342 private PrototypeMemberDeclaration(Node lhs, Node node) {
343 this.lhs = lhs;
344 this.memberName = NodeUtil.getPrototypePropertyName(lhs);
345 this.node = node;
346 this.qualifiedClassName =
347 NodeUtil.getPrototypeClassName(lhs).getQualifiedName();
348 }
349
350 private boolean isSameClass(PrototypeMemberDeclaration other) {
351 return qualifiedClassName.equals(other.qualifiedClassName);
352 }
353
354 /**
355 * @return A prototype member declaration representation if there is one
356 * else it returns {@code null}.
357 */
358 private static PrototypeMemberDeclaration extractDeclaration(Node n) {
359 if (!NodeUtil.isPrototypePropertyDeclaration(n)) {
360 return null;
361 }
362 Node lhs = n.getFirstChild().getFirstChild();
363 return new PrototypeMemberDeclaration(lhs, n);
364 }
365 }
366 }