Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2006 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.Predicates;
21 import com.google.common.collect.Iterables;
22 import com.google.common.collect.Lists;
23 import com.google.common.collect.Sets;
24 import com.google.javascript.jscomp.GlobalNamespace.Name;
25 import com.google.javascript.jscomp.GlobalNamespace.Ref;
26 import com.google.javascript.jscomp.GlobalNamespace.Ref.Type;
27 import com.google.javascript.jscomp.ReferenceCollectingCallback;
28 import com.google.javascript.jscomp.ReferenceCollectingCallback.ReferenceCollection;
29 import com.google.javascript.jscomp.Scope;
30 import com.google.javascript.jscomp.Scope.Var;
31 import com.google.javascript.rhino.IR;
32 import com.google.javascript.rhino.JSDocInfo;
33 import com.google.javascript.rhino.Node;
34 import com.google.javascript.rhino.Token;
35 import com.google.javascript.rhino.TokenStream;
36 import com.google.javascript.rhino.jstype.JSType;
37
38 import java.util.ArrayDeque;
39 import java.util.Deque;
40 import java.util.List;
41 import java.util.Map;
42 import java.util.Set;
43
44 /**
45 * Flattens global objects/namespaces by replacing each '.' with '$' in
46 * their names. This reduces the number of property lookups the browser has
47 * to do and allows the {@link RenameVars} pass to shorten namespaced names.
48 * For example, goog.events.handleEvent() -> goog$events$handleEvent() -> Za().
49 *
50 * <p>If a global object's name is assigned to more than once, or if a property
51 * is added to the global object in a complex expression, then none of its
52 * properties will be collapsed (for safety/correctness).
53 *
54 * <p>If, after a global object is declared, it is never referenced except when
55 * its properties are read or set, then the object will be removed after its
56 * properties have been collapsed.
57 *
58 * <p>Uninitialized variable stubs are created at a global object's declaration
59 * site for any of its properties that are added late in a local scope.
60 *
61 * <p>If, after an object is declared, it is referenced directly in a way that
62 * might create an alias for it, then none of its properties will be collapsed.
63 * This behavior is a safeguard to prevent the values associated with the
64 * flattened names from getting out of sync with the object's actual property
65 * values. For example, in the following case, an alias a$b, if created, could
66 * easily keep the value 0 even after a.b became 5:
67 * <code> a = {b: 0}; c = a; c.b = 5; </code>.
68 *
69 * <p>This pass doesn't flatten property accesses of the form: a[b].
70 *
71 * <p>For lots of examples, see the unit test.
72 *
73 */
74 class CollapseProperties implements CompilerPass {
75
76 // Warnings
77 static final DiagnosticType UNSAFE_NAMESPACE_WARNING =
78 DiagnosticType.warning(
79 "JSC_UNSAFE_NAMESPACE",
80 "incomplete alias created for namespace {0}");
81
82 static final DiagnosticType NAMESPACE_REDEFINED_WARNING =
83 DiagnosticType.warning(
84 "JSC_NAMESPACE_REDEFINED",
85 "namespace {0} should not be redefined");
86
87 static final DiagnosticType UNSAFE_THIS = DiagnosticType.warning(
88 "JSC_UNSAFE_THIS",
89 "dangerous use of 'this' in static method {0}");
90
91 private AbstractCompiler compiler;
92
93 /** Global namespace tree */
94 private List<Name> globalNames;
95
96 /** Maps names (e.g. "a.b.c") to nodes in the global namespace tree */
97 private Map<String, Name> nameMap;
98
99 private final boolean collapsePropertiesOnExternTypes;
100 private final boolean inlineAliases;
101
102 /**
103 * Creates an instance.
104 *
105 * @param compiler The JSCompiler, for reporting code changes
106 * @param collapsePropertiesOnExternTypes if true, will rename user-defined
107 * static properties on externed typed. E.g. String.foo.
108 * @param inlineAliases Whether we're allowed to inline local aliases of
109 * namespaces, etc.
110 */
111 CollapseProperties(AbstractCompiler compiler,
112 boolean collapsePropertiesOnExternTypes, boolean inlineAliases) {
113 this.compiler = compiler;
114 this.collapsePropertiesOnExternTypes = collapsePropertiesOnExternTypes;
115 this.inlineAliases = inlineAliases;
116 }
117
118 @Override
119 public void process(Node externs, Node root) {
120 GlobalNamespace namespace;
121 if (collapsePropertiesOnExternTypes) {
122 namespace = new GlobalNamespace(compiler, externs, root);
123 } else {
124 namespace = new GlobalNamespace(compiler, root);
125 }
126
127 if (inlineAliases) {
128 inlineAliases(namespace);
129 }
130 nameMap = namespace.getNameIndex();
131 globalNames = namespace.getNameForest();
132 checkNamespaces();
133
134 for (Name n : globalNames) {
135 flattenReferencesToCollapsibleDescendantNames(n, n.getBaseName());
136 }
137
138 // We collapse property definitions after collapsing property references
139 // because this step can alter the parse tree above property references,
140 // invalidating the node ancestry stored with each reference.
141 for (Name n : globalNames) {
142 collapseDeclarationOfNameAndDescendants(n, n.getBaseName());
143 }
144 }
145
146 /**
147 * For each qualified name N in the global scope, we check if:
148 * (a) No ancestor of N is ever aliased or assigned an unknown value type.
149 * (If N = "a.b.c", "a" and "a.b" are never aliased).
150 * (b) N has exactly one write, and it lives in the global scope.
151 * (c) N is aliased in a local scope.
152 *
153 * If (a) is true, then GlobalNamespace must know all the writes to N.
154 * If (a) and (b) are true, then N cannot change during the execution of
155 * a local scope.
156 * If (a) and (b) and (c) are true, then the alias can be inlined if the
157 * alias obeys the usual rules for how we decide whether a variable is
158 * inlineable.
159 * @see InlineVariables
160 */
161 private void inlineAliases(GlobalNamespace namespace) {
162 // Invariant: All the names in the worklist meet condition (a).
163 Deque<Name> workList = new ArrayDeque<Name>(namespace.getNameForest());
164 while (!workList.isEmpty()) {
165 Name name = workList.pop();
166
167 // Don't attempt to inline a getter or setter property as a variable.
168 if (name.type == Name.Type.GET || name.type == Name.Type.SET) {
169 continue;
170 }
171
172 if (name.globalSets == 1 && name.localSets == 0 &&
173 name.aliasingGets > 0) {
174 // {@code name} meets condition (b). Find all of its local aliases
175 // and try to inline them.
176 List<Ref> refs = Lists.newArrayList(name.getRefs());
177 for (Ref ref : refs) {
178 if (ref.type == Type.ALIASING_GET && ref.scope.isLocal()) {
179 // {@code name} meets condition (c). Try to inline it.
180 if (inlineAliasIfPossible(ref, namespace)) {
181 name.removeRef(ref);
182 }
183 }
184 }
185 }
186
187 // Check if {@code name} has any aliases left after the
188 // local-alias-inlining above.
189 if ((name.type == Name.Type.OBJECTLIT ||
190 name.type == Name.Type.FUNCTION) &&
191 name.aliasingGets == 0 && name.props != null) {
192 // All of {@code name}'s children meet condition (a), so they can be
193 // added to the worklist.
194 workList.addAll(name.props);
195 }
196 }
197 }
198
199 private boolean inlineAliasIfPossible(Ref alias, GlobalNamespace namespace) {
200 // Ensure that the alias is assigned to a local variable at that
201 // variable's declaration. If the alias's parent is a NAME,
202 // then the NAME must be the child of a VAR node, and we must
203 // be in a VAR assignment.
204 Node aliasParent = alias.node.getParent();
205 if (aliasParent.isName()) {
206 // Ensure that the local variable is well defined and never reassigned.
207 Scope scope = alias.scope;
208 Var aliasVar = scope.getVar(aliasParent.getString());
209 ReferenceCollectingCallback collector =
210 new ReferenceCollectingCallback(compiler,
211 ReferenceCollectingCallback.DO_NOTHING_BEHAVIOR,
212 Predicates.<Var>equalTo(aliasVar));
213 (new NodeTraversal(compiler, collector)).traverseAtScope(scope);
214
215 ReferenceCollection aliasRefs = collector.getReferences(aliasVar);
216 if (aliasRefs.isWellDefined()
217 && aliasRefs.firstReferenceIsAssigningDeclaration()
218 && aliasRefs.isAssignedOnceInLifetime()) {
219 // The alias is well-formed, so do the inlining now.
220 int size = aliasRefs.references.size();
221 Set<Node> newNodes = Sets.newHashSetWithExpectedSize(size - 1);
222 for (int i = 1; i < size; i++) {
223 ReferenceCollectingCallback.Reference aliasRef =
224 aliasRefs.references.get(i);
225
226 Node newNode = alias.node.cloneTree();
227 aliasRef.getParent().replaceChild(aliasRef.getNode(), newNode);
228 newNodes.add(newNode);
229 }
230
231 // just set the original alias to null.
232 aliasParent.replaceChild(alias.node, IR.nullNode());
233 compiler.reportCodeChange();
234
235 // Inlining the variable may have introduced new references
236 // to descendants of {@code name}. So those need to be collected now.
237 namespace.scanNewNodes(alias.scope, newNodes);
238 return true;
239 }
240 }
241
242 return false;
243 }
244
245 /**
246 * Runs through all namespaces (prefixes of classes and enums), and checks if
247 * any of them have been used in an unsafe way.
248 */
249 private void checkNamespaces() {
250 for (Name name : nameMap.values()) {
251 if (name.isNamespace() &&
252 (name.aliasingGets > 0 || name.localSets + name.globalSets > 1 ||
253 name.deleteProps > 0)) {
254 boolean initialized = name.getDeclaration() != null;
255 for (Ref ref : name.getRefs()) {
256 if (ref == name.getDeclaration()) {
257 continue;
258 }
259
260 if (ref.type == Ref.Type.DELETE_PROP) {
261 if (initialized) {
262 warnAboutNamespaceRedefinition(name, ref);
263 }
264 } else if (
265 ref.type == Ref.Type.SET_FROM_GLOBAL ||
266 ref.type == Ref.Type.SET_FROM_LOCAL) {
267 if (initialized) {
268 warnAboutNamespaceRedefinition(name, ref);
269 }
270
271 initialized = true;
272 } else if (ref.type == Ref.Type.ALIASING_GET) {
273 warnAboutNamespaceAliasing(name, ref);
274 }
275 }
276 }
277 }
278 }
279
280 /**
281 * Reports a warning because a namespace was aliased.
282 *
283 * @param nameObj A namespace that is being aliased
284 * @param ref The reference that forced the alias
285 */
286 private void warnAboutNamespaceAliasing(Name nameObj, Ref ref) {
287 compiler.report(
288 JSError.make(ref.getSourceName(), ref.node,
289 UNSAFE_NAMESPACE_WARNING, nameObj.getFullName()));
290 }
291
292 /**
293 * Reports a warning because a namespace was redefined.
294 *
295 * @param nameObj A namespace that is being redefined
296 * @param ref The reference that set the namespace
297 */
298 private void warnAboutNamespaceRedefinition(Name nameObj, Ref ref) {
299 compiler.report(
300 JSError.make(ref.getSourceName(), ref.node,
301 NAMESPACE_REDEFINED_WARNING, nameObj.getFullName()));
302 }
303
304 /**
305 * Flattens all references to collapsible properties of a global name except
306 * their initial definitions. Recurses on subnames.
307 *
308 * @param n An object representing a global name
309 * @param alias The flattened name for {@code n}
310 */
311 private void flattenReferencesToCollapsibleDescendantNames(
312 Name n, String alias) {
313 if (n.props == null) return;
314
315 for (Name p : n.props) {
316 String propAlias = appendPropForAlias(alias, p.getBaseName());
317
318 if (p.canCollapse()) {
319 flattenReferencesTo(p, propAlias);
320 } else if (p.isSimpleStubDeclaration()) {
321 flattenSimpleStubDeclaration(p, propAlias);
322 }
323
324 flattenReferencesToCollapsibleDescendantNames(p, propAlias);
325 }
326 }
327
328
329 /**
330 * Flattens a stub declaration.
331 * This is mostly a hack to support legacy users.
332 */
333 private void flattenSimpleStubDeclaration(Name name, String alias) {
334 Ref ref = Iterables.getOnlyElement(name.getRefs());
335 Node nameNode = NodeUtil.newName(
336 compiler.getCodingConvention(), alias, ref.node,
337 name.getFullName());
338 Node varNode = IR.var(nameNode).copyInformationFrom(nameNode);
339
340 Preconditions.checkState(
341 ref.node.getParent().isExprResult());
342 Node parent = ref.node.getParent();
343 Node gramps = parent.getParent();
344 gramps.replaceChild(parent, varNode);
345 compiler.reportCodeChange();
346 }
347
348
349 /**
350 * Flattens all references to a collapsible property of a global name except
351 * its initial definition.
352 *
353 * @param n A global property name (e.g. "a.b" or "a.b.c.d")
354 * @param alias The flattened name (e.g. "a$b" or "a$b$c$d")
355 */
356 private void flattenReferencesTo(Name n, String alias) {
357 String originalName = n.getFullName();
358 for (Ref r : n.getRefs()) {
359 if (r == n.getDeclaration()) {
360 // Declarations are handled separately.
361 continue;
362 }
363
364 Node rParent = r.node.getParent();
365
366 // There are two cases when we shouldn't flatten a reference:
367 // 1) Object literal keys, because duplicate keys show up as refs.
368 // 2) References inside a complex assign. (a = x.y = 0). These are
369 // called TWIN references, because they show up twice in the
370 // reference list. Only collapse the set, not the alias.
371 if (!NodeUtil.isObjectLitKey(r.node) &&
372 (r.getTwin() == null || r.isSet())) {
373 flattenNameRef(alias, r.node, rParent, originalName);
374 }
375 }
376
377 // Flatten all occurrences of a name as a prefix of its subnames. For
378 // example, if {@code n} corresponds to the name "a.b", then "a.b" will be
379 // replaced with "a$b" in all occurrences of "a.b.c", "a.b.c.d", etc.
380 if (n.props != null) {
381 for (Name p : n.props) {
382 flattenPrefixes(alias, p, 1);
383 }
384 }
385 }
386
387 /**
388 * Flattens all occurrences of a name as a prefix of subnames beginning
389 * with a particular subname.
390 *
391 * @param n A global property name (e.g. "a.b.c.d")
392 * @param alias A flattened prefix name (e.g. "a$b")
393 * @param depth The difference in depth between the property name and
394 * the prefix name (e.g. 2)
395 */
396 private void flattenPrefixes(String alias, Name n, int depth) {
397 // Only flatten the prefix of a name declaration if the name being
398 // initialized is fully qualified (i.e. not an object literal key).
399 String originalName = n.getFullName();
400 Ref decl = n.getDeclaration();
401 if (decl != null && decl.node != null &&
402 decl.node.isGetProp()) {
403 flattenNameRefAtDepth(alias, decl.node, depth, originalName);
404 }
405
406 for (Ref r : n.getRefs()) {
407 if (r == decl) {
408 // Declarations are handled separately.
409 continue;
410 }
411
412 // References inside a complex assign (a = x.y = 0)
413 // have twins. We should only flatten one of the twins.
414 if (r.getTwin() == null || r.isSet()) {
415 flattenNameRefAtDepth(alias, r.node, depth, originalName);
416 }
417 }
418
419 if (n.props != null) {
420 for (Name p : n.props) {
421 flattenPrefixes(alias, p, depth + 1);
422 }
423 }
424 }
425
426 /**
427 * Flattens a particular prefix of a single name reference.
428 *
429 * @param alias A flattened prefix name (e.g. "a$b")
430 * @param n The node corresponding to a subproperty name (e.g. "a.b.c.d")
431 * @param depth The difference in depth between the property name and
432 * the prefix name (e.g. 2)
433 * @param originalName String version of the property name.
434 */
435 private void flattenNameRefAtDepth(String alias, Node n, int depth,
436 String originalName) {
437 // This method has to work for both GETPROP chains and, in rare cases,
438 // OBJLIT keys, possibly nested. That's why we check for children before
439 // proceeding. In the OBJLIT case, we don't need to do anything.
440 int nType = n.getType();
441 boolean isQName = nType == Token.NAME || nType == Token.GETPROP;
442 boolean isObjKey = NodeUtil.isObjectLitKey(n);
443 Preconditions.checkState(isObjKey || isQName);
444 if (isQName) {
445 for (int i = 1; i < depth && n.hasChildren(); i++) {
446 n = n.getFirstChild();
447 }
448 if (n.hasChildren()) {
449 flattenNameRef(alias, n.getFirstChild(), n, originalName);
450 }
451 }
452 }
453
454 /**
455 * Replaces a GETPROP a.b.c with a NAME a$b$c.
456 *
457 * @param alias A flattened prefix name (e.g. "a$b")
458 * @param n The GETPROP node corresponding to the original name (e.g. "a.b")
459 * @param parent {@code n}'s parent
460 * @param originalName String version of the property name.
461 */
462 private void flattenNameRef(String alias, Node n, Node parent,
463 String originalName) {
464 // BEFORE:
465 // getprop
466 // getprop
467 // name a
468 // string b
469 // string c
470 // AFTER:
471 // name a$b$c
472 Node ref = NodeUtil.newName(
473 compiler.getCodingConvention(), alias, n, originalName);
474 NodeUtil.copyNameAnnotations(n.getLastChild(), ref);
475 if (parent.isCall() && n == parent.getFirstChild()) {
476 // The node was a call target, we are deliberately flatten these as
477 // we node the "this" isn't provided by the namespace. Mark it as such:
478 parent.putBooleanProp(Node.FREE_CALL, true);
479 }
480
481 JSType type = n.getJSType();
482 if (type != null) {
483 ref.setJSType(type);
484 }
485 parent.replaceChild(n, ref);
486 compiler.reportCodeChange();
487 }
488
489 /**
490 * Collapses definitions of the collapsible properties of a global name.
491 * Recurses on subnames that also represent JavaScript objects with
492 * collapsible properties.
493 *
494 * @param n A node representing a global name
495 * @param alias The flattened name for {@code n}
496 */
497 private void collapseDeclarationOfNameAndDescendants(Name n, String alias) {
498 boolean canCollapseChildNames = n.canCollapseUnannotatedChildNames();
499
500 // Handle this name first so that nested object literals get unrolled.
501 if (n.canCollapse()) {
502 updateObjLitOrFunctionDeclaration(n, alias, canCollapseChildNames);
503 }
504
505 if (n.props != null) {
506 for (Name p : n.props) {
507 // Recurse first so that saved node ancestries are intact when needed.
508 collapseDeclarationOfNameAndDescendants(
509 p, appendPropForAlias(alias, p.getBaseName()));
510
511 if (!p.inExterns && canCollapseChildNames &&
512 p.getDeclaration() != null &&
513 p.canCollapse() &&
514 p.getDeclaration().node != null &&
515 p.getDeclaration().node.getParent() != null &&
516 p.getDeclaration().node.getParent().isAssign()) {
517 updateSimpleDeclaration(
518 appendPropForAlias(alias, p.getBaseName()), p, p.getDeclaration());
519 }
520 }
521 }
522 }
523
524 /**
525 * Updates the initial assignment to a collapsible property at global scope
526 * by changing it to a variable declaration (e.g. a.b = 1 -> var a$b = 1).
527 * The property's value may either be a primitive or an object literal or
528 * function whose properties aren't collapsible.
529 *
530 * @param alias The flattened property name (e.g. "a$b")
531 * @param refName The name for the reference being updated.
532 * @param ref An object containing information about the assignment getting
533 * updated
534 */
535 private void updateSimpleDeclaration(String alias, Name refName, Ref ref) {
536 Node rvalue = ref.node.getNext();
537 Node parent = ref.node.getParent();
538 Node gramps = parent.getParent();
539 Node greatGramps = gramps.getParent();
540
541 if (rvalue != null && rvalue.isFunction()) {
542 checkForHosedThisReferences(rvalue, refName.docInfo, refName);
543 }
544
545 // Create the new alias node.
546 Node nameNode = NodeUtil.newName(
547 compiler.getCodingConvention(), alias, gramps.getFirstChild(),
548 refName.getFullName());
549 NodeUtil.copyNameAnnotations(ref.node.getLastChild(), nameNode);
550
551 if (gramps.isExprResult()) {
552 // BEFORE: a.b.c = ...;
553 // exprstmt
554 // assign
555 // getprop
556 // getprop
557 // name a
558 // string b
559 // string c
560 // NODE
561 // AFTER: var a$b$c = ...;
562 // var
563 // name a$b$c
564 // NODE
565
566 // Remove the r-value (NODE).
567 parent.removeChild(rvalue);
568 nameNode.addChildToFront(rvalue);
569
570 Node varNode = IR.var(nameNode);
571 greatGramps.replaceChild(gramps, varNode);
572 } else {
573 // This must be a complex assignment.
574 Preconditions.checkNotNull(ref.getTwin());
575
576 // BEFORE:
577 // ... (x.y = 3);
578 //
579 // AFTER:
580 // var x$y;
581 // ... (x$y = 3);
582
583 Node current = gramps;
584 Node currentParent = gramps.getParent();
585 for (; !currentParent.isScript() &&
586 !currentParent.isBlock();
587 current = currentParent,
588 currentParent = currentParent.getParent()) {}
589
590 // Create a stub variable declaration right
591 // before the current statement.
592 Node stubVar = IR.var(nameNode.cloneTree())
593 .copyInformationFrom(nameNode);
594 currentParent.addChildBefore(stubVar, current);
595
596 parent.replaceChild(ref.node, nameNode);
597 }
598
599 compiler.reportCodeChange();
600 }
601
602 /**
603 * Updates the first initialization (a.k.a "declaration") of a global name.
604 * This involves flattening the global name (if it's not just a global
605 * variable name already), collapsing object literal keys into global
606 * variables, declaring stub global variables for properties added later
607 * in a local scope.
608 *
609 * It may seem odd that this function also takes care of declaring stubs
610 * for direct children. The ultimate goal of this function is to eliminate
611 * the global name entirely (when possible), so that "middlemen" namespaces
612 * disappear, and to do that we need to make sure that all the direct children
613 * will be collapsed as well.
614 *
615 * @param n An object representing a global name (e.g. "a", "a.b.c")
616 * @param alias The flattened name for {@code n} (e.g. "a", "a$b$c")
617 * @param canCollapseChildNames Whether it's possible to collapse children of
618 * this name. (This is mostly passed for convenience; it's equivalent to
619 * n.canCollapseChildNames()).
620 */
621 private void updateObjLitOrFunctionDeclaration(
622 Name n, String alias, boolean canCollapseChildNames) {
623 Ref decl = n.getDeclaration();
624 if (decl == null) {
625 // Some names do not have declarations, because they
626 // are only defined in local scopes.
627 return;
628 }
629
630 if (decl.getTwin() != null) {
631 // Twin declarations will get handled when normal references
632 // are handled.
633 return;
634 }
635
636 switch (decl.node.getParent().getType()) {
637 case Token.ASSIGN:
638 updateObjLitOrFunctionDeclarationAtAssignNode(
639 n, alias, canCollapseChildNames);
640 break;
641 case Token.VAR:
642 updateObjLitOrFunctionDeclarationAtVarNode(n, canCollapseChildNames);
643 break;
644 case Token.FUNCTION:
645 updateFunctionDeclarationAtFunctionNode(n, canCollapseChildNames);
646 break;
647 }
648 }
649
650 /**
651 * Updates the first initialization (a.k.a "declaration") of a global name
652 * that occurs at an ASSIGN node. See comment for
653 * {@link #updateObjLitOrFunctionDeclaration}.
654 *
655 * @param n An object representing a global name (e.g. "a", "a.b.c")
656 * @param alias The flattened name for {@code n} (e.g. "a", "a$b$c")
657 */
658 private void updateObjLitOrFunctionDeclarationAtAssignNode(
659 Name n, String alias, boolean canCollapseChildNames) {
660 // NOTE: It's important that we don't add additional nodes
661 // (e.g. a var node before the exprstmt) because the exprstmt might be
662 // the child of an if statement that's not inside a block).
663
664 Ref ref = n.getDeclaration();
665 Node rvalue = ref.node.getNext();
666 Node varNode = new Node(Token.VAR);
667 Node varParent = ref.node.getAncestor(3);
668 Node gramps = ref.node.getAncestor(2);
669 boolean isObjLit = rvalue.isObjectLit();
670 boolean insertedVarNode = false;
671
672 if (isObjLit && n.canEliminate()) {
673 // Eliminate the object literal altogether.
674 varParent.replaceChild(gramps, varNode);
675 ref.node = null;
676 insertedVarNode = true;
677
678 } else if (!n.isSimpleName()) {
679 // Create a VAR node to declare the name.
680 if (rvalue.isFunction()) {
681 checkForHosedThisReferences(rvalue, n.docInfo, n);
682 }
683
684 ref.node.getParent().removeChild(rvalue);
685
686 Node nameNode = NodeUtil.newName(
687 compiler.getCodingConvention(),
688 alias, ref.node.getAncestor(2), n.getFullName());
689
690 JSDocInfo info = ref.node.getParent().getJSDocInfo();
691 if (ref.node.getLastChild().getBooleanProp(Node.IS_CONSTANT_NAME) ||
692 (info != null && info.isConstant())) {
693 nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
694 }
695
696 if (info != null) {
697 varNode.setJSDocInfo(info);
698 }
699 varNode.addChildToBack(nameNode);
700 nameNode.addChildToFront(rvalue);
701 varParent.replaceChild(gramps, varNode);
702
703 // Update the node ancestry stored in the reference.
704 ref.node = nameNode;
705 insertedVarNode = true;
706 }
707
708 if (canCollapseChildNames) {
709 if (isObjLit) {
710 declareVarsForObjLitValues(
711 n, alias, rvalue,
712 varNode, varParent.getChildBefore(varNode), varParent);
713 }
714
715 addStubsForUndeclaredProperties(n, alias, varParent, varNode);
716 }
717
718 if (insertedVarNode) {
719 if (!varNode.hasChildren()) {
720 varParent.removeChild(varNode);
721 }
722 compiler.reportCodeChange();
723 }
724 }
725
726 /**
727 * Warns about any references to "this" in the given FUNCTION. The function
728 * is getting collapsed, so the references will change.
729 */
730 private void checkForHosedThisReferences(Node function, JSDocInfo docInfo,
731 final Name name) {
732 // A function is getting collapsed. Make sure that if it refers to
733 // "this", it must be a constructor or documented with @this.
734 if (docInfo == null ||
735 (!docInfo.isConstructor() && !docInfo.hasThisType())) {
736 NodeTraversal.traverse(compiler, function.getLastChild(),
737 new NodeTraversal.AbstractShallowCallback() {
738 @Override
739 public void visit(NodeTraversal t, Node n, Node parent) {
740 if (n.isThis()) {
741 compiler.report(
742 JSError.make(name.getDeclaration().getSourceName(), n,
743 UNSAFE_THIS, name.getFullName()));
744 }
745 }
746 });
747 }
748 }
749
750 /**
751 * Updates the first initialization (a.k.a "declaration") of a global name
752 * that occurs at a VAR node. See comment for
753 * {@link #updateObjLitOrFunctionDeclaration}.
754 *
755 * @param n An object representing a global name (e.g. "a")
756 */
757 private void updateObjLitOrFunctionDeclarationAtVarNode(
758 Name n, boolean canCollapseChildNames) {
759 if (!canCollapseChildNames) {
760 return;
761 }
762
763 Ref ref = n.getDeclaration();
764 String name = ref.node.getString();
765 Node rvalue = ref.node.getFirstChild();
766 Node varNode = ref.node.getParent();
767 Node gramps = varNode.getParent();
768
769 boolean isObjLit = rvalue.isObjectLit();
770 int numChanges = 0;
771
772 if (isObjLit) {
773 numChanges += declareVarsForObjLitValues(
774 n, name, rvalue, varNode, gramps.getChildBefore(varNode),
775 gramps);
776 }
777
778 numChanges += addStubsForUndeclaredProperties(n, name, gramps, varNode);
779
780 if (isObjLit && n.canEliminate()) {
781 varNode.removeChild(ref.node);
782 if (!varNode.hasChildren()) {
783 gramps.removeChild(varNode);
784 }
785 numChanges++;
786
787 // Clear out the object reference, since we've eliminated it from the
788 // parse tree.
789 ref.node = null;
790 }
791
792 if (numChanges > 0) {
793 compiler.reportCodeChange();
794 }
795 }
796
797 /**
798 * Updates the first initialization (a.k.a "declaration") of a global name
799 * that occurs at a FUNCTION node. See comment for
800 * {@link #updateObjLitOrFunctionDeclaration}.
801 *
802 * @param n An object representing a global name (e.g. "a")
803 */
804 private void updateFunctionDeclarationAtFunctionNode(
805 Name n, boolean canCollapseChildNames) {
806 if (!canCollapseChildNames) {
807 return;
808 }
809
810 Ref ref = n.getDeclaration();
811 String fnName = ref.node.getString();
812 addStubsForUndeclaredProperties(
813 n, fnName, ref.node.getAncestor(2), ref.node.getParent());
814 }
815
816 /**
817 * Declares global variables to serve as aliases for the values in an object
818 * literal, optionally removing all of the object literal's keys and values.
819 *
820 * @param alias The object literal's flattened name (e.g. "a$b$c")
821 * @param objlit The OBJLIT node
822 * @param varNode The VAR node to which new global variables should be added
823 * as children
824 * @param nameToAddAfter The child of {@code varNode} after which new
825 * variables should be added (may be null)
826 * @param varParent {@code varNode}'s parent
827 * @return The number of variables added
828 */
829 private int declareVarsForObjLitValues(
830 Name objlitName, String alias, Node objlit, Node varNode,
831 Node nameToAddAfter, Node varParent) {
832 int numVars = 0;
833 int arbitraryNameCounter = 0;
834 boolean discardKeys = !objlitName.shouldKeepKeys();
835
836 for (Node key = objlit.getFirstChild(), nextKey; key != null;
837 key = nextKey) {
838 Node value = key.getFirstChild();
839 nextKey = key.getNext();
840
841 // A get or a set can not be rewritten as a VAR.
842 if (key.isGetterDef() || key.isSetterDef()) {
843 continue;
844 }
845
846 // We generate arbitrary names for keys that aren't valid JavaScript
847 // identifiers, since those keys are never referenced. (If they were,
848 // this object literal's child names wouldn't be collapsible.) The only
849 // reason that we don't eliminate them entirely is the off chance that
850 // their values are expressions that have side effects.
851 boolean isJsIdentifier = !key.isNumber() &&
852 TokenStream.isJSIdentifier(key.getString());
853 String propName = isJsIdentifier ?
854 key.getString() : String.valueOf(++arbitraryNameCounter);
855
856 // If the name cannot be collapsed, skip it.
857 String qName = objlitName.getFullName() + '.' + propName;
858 Name p = nameMap.get(qName);
859 if (p != null && !p.canCollapse()) {
860 continue;
861 }
862
863 String propAlias = appendPropForAlias(alias, propName);
864 Node refNode = null;
865 if (discardKeys) {
866 objlit.removeChild(key);
867 value.detachFromParent();
868 } else {
869 // Substitute a reference for the value.
870 refNode = IR.name(propAlias);
871 if (key.getBooleanProp(Node.IS_CONSTANT_NAME)) {
872 refNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
873 }
874
875 key.replaceChild(value, refNode);
876 }
877
878 // Declare the collapsed name as a variable with the original value.
879 Node nameNode = IR.name(propAlias);
880 nameNode.addChildToFront(value);
881 if (key.getBooleanProp(Node.IS_CONSTANT_NAME)) {
882 nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
883 }
884 Node newVar = IR.var(nameNode)
885 .copyInformationFromForTree(key);
886 if (nameToAddAfter != null) {
887 varParent.addChildAfter(newVar, nameToAddAfter);
888 } else {
889 varParent.addChildBefore(newVar, varNode);
890 }
891 compiler.reportCodeChange();
892 nameToAddAfter = newVar;
893
894 // Update the global name's node ancestry if it hasn't already been
895 // done. (Duplicate keys in an object literal can bring us here twice
896 // for the same global name.)
897 if (isJsIdentifier && p != null) {
898 if (!discardKeys) {
899 Ref newAlias =
900 p.getDeclaration().cloneAndReclassify(Ref.Type.ALIASING_GET);
901 newAlias.node = refNode;
902 p.addRef(newAlias);
903 }
904
905 p.getDeclaration().node = nameNode;
906
907 if (value.isFunction()) {
908 checkForHosedThisReferences(value, value.getJSDocInfo(), p);
909 }
910 }
911
912 numVars++;
913 }
914 return numVars;
915 }
916
917 /**
918 * Adds global variable "stubs" for any properties of a global name that are
919 * only set in a local scope or read but never set.
920 *
921 * @param n An object representing a global name (e.g. "a", "a.b.c")
922 * @param alias The flattened name of the object whose properties we are
923 * adding stubs for (e.g. "a$b$c")
924 * @param parent The node to which new global variables should be added
925 * as children
926 * @param addAfter The child of after which new
927 * variables should be added (may be null)
928 * @return The number of variables added
929 */
930 private int addStubsForUndeclaredProperties(
931 Name n, String alias, Node parent, Node addAfter) {
932 Preconditions.checkState(n.canCollapseUnannotatedChildNames());
933 Preconditions.checkArgument(NodeUtil.isStatementBlock(parent));
934 Preconditions.checkNotNull(addAfter);
935 int numStubs = 0;
936 if (n.props != null) {
937 for (Name p : n.props) {
938 if (p.needsToBeStubbed()) {
939 String propAlias = appendPropForAlias(alias, p.getBaseName());
940 Node nameNode = IR.name(propAlias);
941 Node newVar = IR.var(nameNode)
942 .copyInformationFromForTree(addAfter);
943 parent.addChildAfter(newVar, addAfter);
944 addAfter = newVar;
945 numStubs++;
946 compiler.reportCodeChange();
947
948 // Determine if this is a constant var by checking the first
949 // reference to it. Don't check the declaration, as it might be null.
950 if (p.getRefs().get(0).node.getLastChild().getBooleanProp(
951 Node.IS_CONSTANT_NAME)) {
952 nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
953 }
954 }
955 }
956 }
957 return numStubs;
958 }
959
960 private static String appendPropForAlias(String root, String prop) {
961 if (prop.indexOf('$') != -1) {
962 // Encode '$' in a property as '$0'. Because '0' cannot be the
963 // start of an identifier, this will never conflict with our
964 // encoding from '.' -> '$'.
965 prop = prop.replace("$", "$0");
966 }
967 return root + '$' + prop;
968 }
969 }