Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2011 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.base.Preconditions;
20 import com.google.common.base.Supplier;
21 import com.google.common.collect.Lists;
22 import com.google.common.collect.Maps;
23 import com.google.common.collect.Sets;
24 import com.google.javascript.jscomp.ReferenceCollectingCallback.Behavior;
25 import com.google.javascript.jscomp.ReferenceCollectingCallback.Reference;
26 import com.google.javascript.jscomp.ReferenceCollectingCallback.ReferenceCollection;
27 import com.google.javascript.jscomp.ReferenceCollectingCallback.ReferenceMap;
28 import com.google.javascript.jscomp.Scope.Var;
29 import com.google.javascript.rhino.IR;
30 import com.google.javascript.rhino.Node;
31 import com.google.javascript.rhino.Token;
32
33 import java.util.Iterator;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Set;
37
38
39 /**
40 * Using the infrastructure provided by {@link ReferenceCollectingCallback},
41 * identify variables that are only ever assigned to object literals
42 * and that are never used in entirety, and expand the objects into
43 * individual variables.
44 *
45 * Based on the InlineVariables pass
46 *
47 */
48 class InlineObjectLiterals implements CompilerPass {
49
50 public static final String VAR_PREFIX = "JSCompiler_object_inline_";
51
52 private final AbstractCompiler compiler;
53
54 private final Supplier<String> safeNameIdSupplier;
55
56 InlineObjectLiterals(
57 AbstractCompiler compiler,
58 Supplier<String> safeNameIdSupplier) {
59 this.compiler = compiler;
60 this.safeNameIdSupplier = safeNameIdSupplier;
61 }
62
63 @Override
64 public void process(Node externs, Node root) {
65 ReferenceCollectingCallback callback = new ReferenceCollectingCallback(
66 compiler, new InliningBehavior());
67 callback.process(externs, root);
68 }
69
70 /**
71 * Builds up information about nodes in each scope. When exiting the
72 * scope, inspects all variables in that scope, and inlines any
73 * that we can.
74 */
75 private class InliningBehavior implements Behavior {
76
77 /**
78 * A list of variables that should not be inlined, because their
79 * reference information is out of sync with the state of the AST.
80 */
81 private final Set<Var> staleVars = Sets.newHashSet();
82
83 @Override
84 public void afterExitScope(NodeTraversal t, ReferenceMap referenceMap) {
85 for (Iterator<Var> it = t.getScope().getVars(); it.hasNext();) {
86 Var v = it.next();
87
88 if (isVarInlineForbidden(v)) {
89 continue;
90 }
91
92 ReferenceCollection referenceInfo = referenceMap.getReferences(v);
93
94 if (isInlinableObject(referenceInfo.references)) {
95 // Blacklist the object itself, as well as any other values
96 // that it refers to, since they will have been moved around.
97 staleVars.add(v);
98
99 Reference init = referenceInfo.getInitializingReference();
100
101 // Split up the object into individual variables if the object
102 // is never referenced directly in full.
103 splitObject(v, init, referenceInfo);
104 }
105 }
106 }
107
108 /**
109 * If there are any variable references in the given node tree,
110 * blacklist them to prevent the pass from trying to inline the
111 * variable. Any code modifications will have potentially made the
112 * ReferenceCollection invalid.
113 */
114 private void blacklistVarReferencesInTree(Node root, final Scope scope) {
115 NodeUtil.visitPreOrder(root, new NodeUtil.Visitor() {
116 @Override
117 public void visit(Node node) {
118 if (node.isName()) {
119 staleVars.add(scope.getVar(node.getString()));
120 }
121 }
122 }, NodeUtil.MATCH_NOT_FUNCTION);
123 }
124
125 /**
126 * Whether the given variable is forbidden from being inlined.
127 */
128 private boolean isVarInlineForbidden(Var var) {
129 // A variable may not be inlined if:
130 // 1) The variable is defined in the externs
131 // 2) The variable is exported,
132 // 3) Don't inline the special RENAME_PROPERTY_FUNCTION_NAME
133 // 4) A reference to the variable has been inlined. We're downstream
134 // of the mechanism that creates variable references, so we don't
135 // have a good way to update the reference. Just punt on it.
136
137 // Additionally, exclude global variables for now.
138
139 return var.isGlobal()
140 || var.isExtern()
141 || compiler.getCodingConvention().isExported(var.name)
142 || RenameProperties.RENAME_PROPERTY_FUNCTION_NAME.equals(var.name)
143 || staleVars.contains(var);
144 }
145
146 /**
147 * Counts the number of direct (full) references to an object.
148 * Specifically, we check for references of the following type:
149 * <pre>
150 * x;
151 * x.fn();
152 * </pre>
153 */
154 private boolean isInlinableObject(List<Reference> refs) {
155 boolean ret = false;
156 Set<String> validProperties = Sets.newHashSet();
157 for (Reference ref : refs) {
158 Node name = ref.getNode();
159 Node parent = ref.getParent();
160 Node gramps = ref.getGrandparent();
161
162 // Ignore most indirect references, like x.y (but not x.y(),
163 // since the function referenced by y might reference 'this').
164 //
165 if (parent.isGetProp()) {
166 Preconditions.checkState(parent.getFirstChild() == name);
167 // A call target may be using the object as a 'this' value.
168 if (gramps.isCall()
169 && gramps.getFirstChild() == parent) {
170 return false;
171 }
172
173 // Deleting a property has different semantics from deleting
174 // a variable, so deleted properties should not be inlined.
175 if (gramps.isDelProp()) {
176 return false;
177 }
178
179 // NOTE(nicksantos): This pass's object-splitting algorithm has
180 // a blind spot. It assumes that if a property isn't defined on an
181 // object, then the value is undefined. This is not true, because
182 // Object.prototype can have arbitrary properties on it.
183 //
184 // We short-circuit this problem by bailing out if we see a reference
185 // to a property that isn't defined on the object literal. This
186 // isn't a perfect algorithm, but it should catch most cases.
187 String propName = parent.getLastChild().getString();
188 if (!validProperties.contains(propName)) {
189 if (NodeUtil.isVarOrSimpleAssignLhs(parent, gramps)) {
190 validProperties.add(propName);
191 } else {
192 return false;
193 }
194 }
195 continue;
196 }
197
198 // Only rewrite VAR declarations or simple assignment statements
199 if (!isVarOrAssignExprLhs(name)) {
200 return false;
201 }
202
203 Node val = ref.getAssignedValue();
204 if (val == null) {
205 // A var with no assignment.
206 continue;
207 }
208
209 // We're looking for object literal assignments only.
210 if (!val.isObjectLit()) {
211 return false;
212 }
213
214 // Make sure that the value is not self-referential. IOW,
215 // disallow things like x = {b: x.a}.
216 //
217 // TODO: Only exclude unorderable self-referential
218 // assignments. i.e. x = {a: x.b, b: x.a} is not orderable,
219 // but x = {a: 1, b: x.a} is.
220 //
221 // Also, ES5 getters/setters aren't handled by this pass.
222 for (Node child = val.getFirstChild(); child != null;
223 child = child.getNext()) {
224 if (child.isGetterDef() ||
225 child.isSetterDef()) {
226 // ES5 get/set not supported.
227 return false;
228 }
229
230 validProperties.add(child.getString());
231
232 Node childVal = child.getFirstChild();
233 // Check if childVal is the parent of any of the passed in
234 // references, as that is how self-referential assignments
235 // will happen.
236 for (Reference t : refs) {
237 Node refNode = t.getParent();
238 while (!NodeUtil.isStatementBlock(refNode)) {
239 if (refNode == childVal) {
240 // There's a self-referential assignment
241 return false;
242 }
243 refNode = refNode.getParent();
244 }
245 }
246 }
247
248
249 // We have found an acceptable object literal assignment. As
250 // long as there are no other assignments that mess things up,
251 // we can inline.
252 ret = true;
253 }
254 return ret;
255 }
256
257 private boolean isVarOrAssignExprLhs(Node n) {
258 Node parent = n.getParent();
259 return parent.isVar() ||
260 (parent.isAssign()
261 && parent.getFirstChild() == n
262 && parent.getParent().isExprResult());
263 }
264
265 /**
266 * Computes a list of ever-referenced keys in the object being
267 * inlined, and returns a mapping of key name -> generated
268 * variable name.
269 */
270 private Map<String, String> computeVarList(
271 ReferenceCollection referenceInfo) {
272 Map<String, String> varmap = Maps.newLinkedHashMap();
273
274 for (Reference ref : referenceInfo.references) {
275 if (ref.isLvalue() || ref.isInitializingDeclaration()) {
276 Node val = ref.getAssignedValue();
277 if (val != null) {
278 Preconditions.checkState(val.isObjectLit());
279 for (Node child = val.getFirstChild(); child != null;
280 child = child.getNext()) {
281 String varname = child.getString();
282 if (varmap.containsKey(varname)) {
283 continue;
284 }
285
286 String var = VAR_PREFIX + varname + "_" +
287 safeNameIdSupplier.get();
288 varmap.put(varname, var);
289 }
290 }
291 } else if (ref.getParent().isVar()) {
292 // This is the var. There is no value.
293 } else {
294 Node getprop = ref.getParent();
295 Preconditions.checkState(getprop.isGetProp());
296
297 // The key being looked up in the original map.
298 String varname = getprop.getLastChild().getString();
299 if (varmap.containsKey(varname)) {
300 continue;
301 }
302
303 String var = VAR_PREFIX + varname + "_" + safeNameIdSupplier.get();
304 varmap.put(varname, var);
305 }
306 }
307
308 return varmap;
309 }
310
311 /**
312 * Populates a map of key names -> initial assigned values. The
313 * object literal these are being pulled from is invalidated as
314 * a result.
315 */
316 private void fillInitialValues(Reference init, Map<String, Node> initvals) {
317 Node object = init.getAssignedValue();
318 Preconditions.checkState(object.isObjectLit());
319 for (Node key = object.getFirstChild(); key != null;
320 key = key.getNext()) {
321 initvals.put(key.getString(), key.removeFirstChild());
322 }
323 }
324
325 /**
326 * Replaces an assignment like x = {...} with t1=a,t2=b,t3=c,true.
327 * Note that the resulting expression will always evaluate to
328 * true, as would the x = {...} expression.
329 */
330 private void replaceAssignmentExpression(Var v, Reference ref,
331 Map<String, String> varmap) {
332 // Compute all of the assignments necessary
333 List<Node> nodes = Lists.newArrayList();
334 Node val = ref.getAssignedValue();
335 blacklistVarReferencesInTree(val, v.scope);
336 Preconditions.checkState(val.isObjectLit());
337 Set<String> all = Sets.newLinkedHashSet(varmap.keySet());
338 for (Node key = val.getFirstChild(); key != null;
339 key = key.getNext()) {
340 String var = key.getString();
341 Node value = key.removeFirstChild();
342 // TODO(user): Copy type information.
343 nodes.add(
344 IR.assign(
345 IR.name(varmap.get(var)),
346 value));
347 all.remove(var);
348 }
349
350 // TODO(user): Better source information.
351 for (String var : all) {
352 nodes.add(
353 IR.assign(
354 IR.name(varmap.get(var)),
355 NodeUtil.newUndefinedNode(null)));
356 }
357
358 Node replacement;
359 if (nodes.isEmpty()) {
360 replacement = IR.trueNode();
361 } else {
362 // All assignments evaluate to true, so make sure that the
363 // expr statement evaluates to true in case it matters.
364 nodes.add(IR.trueNode());
365
366 // Join these using COMMA. A COMMA node must have 2 children, so we
367 // create a tree. In the tree the first child be the COMMA to match
368 // the parser, otherwise tree equality tests fail.
369 nodes = Lists.reverse(nodes);
370 replacement = new Node(Token.COMMA);
371 Node cur = replacement;
372 int i;
373 for (i = 0; i < nodes.size() - 2; i++) {
374 cur.addChildToFront(nodes.get(i));
375 Node t = new Node(Token.COMMA);
376 cur.addChildToFront(t);
377 cur = t;
378 }
379 cur.addChildToFront(nodes.get(i));
380 cur.addChildToFront(nodes.get(i + 1));
381 }
382
383 Node replace = ref.getParent();
384 replacement.copyInformationFromForTree(replace);
385
386 if (replace.isVar()) {
387 replace.getParent().replaceChild(
388 replace, NodeUtil.newExpr(replacement));
389 } else {
390 replace.getParent().replaceChild(replace, replacement);
391 }
392 }
393
394 /**
395 * Splits up the object literal into individual variables, and
396 * updates all uses.
397 */
398 private void splitObject(Var v, Reference init,
399 ReferenceCollection referenceInfo) {
400 // First figure out the FULL set of possible keys, so that they
401 // can all be properly set as necessary.
402 Map<String, String> varmap = computeVarList(referenceInfo);
403
404 Map<String, Node> initvals = Maps.newHashMap();
405 // Figure out the top-level of the var assign node. If it's a plain
406 // ASSIGN, then there's an EXPR_STATEMENT above it, if it's a
407 // VAR then it should be directly replaced.
408 Node vnode;
409 boolean defined = referenceInfo.isWellDefined() &&
410 init.getParent().isVar();
411 if (defined) {
412 vnode = init.getParent();
413 fillInitialValues(init, initvals);
414 } else {
415 // TODO(user): More test / rewrite this part.
416 // Find the beginning of the function / script.
417 vnode = v.getScope().getRootNode().getLastChild().getFirstChild();
418 }
419
420 for (Map.Entry<String, String> entry : varmap.entrySet()) {
421 Node val = initvals.get(entry.getKey());
422 Node varnode = NodeUtil.newVarNode(entry.getValue(), val);
423 if (val == null) {
424 // is this right?
425 varnode.copyInformationFromForTree(vnode);
426 } else {
427 blacklistVarReferencesInTree(val, v.scope);
428 }
429 vnode.getParent().addChildBefore(varnode, vnode);
430 }
431
432 if (defined) {
433 vnode.getParent().removeChild(vnode);
434 }
435
436 for (Reference ref : referenceInfo.references) {
437 // The init/decl have already been converted.
438 if (defined && ref == init) continue;
439
440 if (ref.isLvalue()) {
441 // Assignments have to be handled specially, since they
442 // expand out into multiple assignments.
443 replaceAssignmentExpression(v, ref, varmap);
444 } else if (ref.getParent().isVar()) {
445 // The old variable declaration. It didn't have a
446 // value. Remove it entirely as it should now be unused.
447 ref.getGrandparent().removeChild(ref.getParent());
448 } else {
449 // Make sure that the reference is a GETPROP as we expect it to be.
450 Node getprop = ref.getParent();
451 Preconditions.checkState(getprop.isGetProp());
452
453 // The key being looked up in the original map.
454 String var = getprop.getChildAtIndex(1).getString();
455
456 // If the variable hasn't already been declared, add an empty
457 // declaration near all the other declarations.
458 Preconditions.checkState(varmap.containsKey(var));
459
460 // Replace the GETPROP node with a NAME.
461 Node replacement = IR.name(varmap.get(var));
462 replacement.copyInformationFrom(getprop);
463 ref.getGrandparent().replaceChild(ref.getParent(), replacement);
464 }
465 }
466
467 compiler.reportCodeChange();
468 }
469 }
470 }