Debian Codegraph @

src/com/google/javascript/jscomp/GlobalNamespace.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 static com.google.javascript.rhino.jstype.JSTypeNative.GLOBAL_THIS;
20
21 import com.google.common.base.Preconditions;
22 import com.google.common.base.Predicate;
23 import com.google.common.collect.ImmutableList;
24 import com.google.common.collect.ImmutableSet;
25 import com.google.common.collect.Lists;
26 import com.google.common.collect.Sets;
27 import com.google.javascript.rhino.JSDocInfo;
28 import com.google.javascript.rhino.Node;
29 import com.google.javascript.rhino.Token;
30 import com.google.javascript.rhino.TokenStream;
31 import com.google.javascript.rhino.jstype.JSType;
32 import com.google.javascript.rhino.jstype.StaticReference;
33 import com.google.javascript.rhino.jstype.StaticScope;
34 import com.google.javascript.rhino.jstype.StaticSlot;
35 import com.google.javascript.rhino.jstype.StaticSourceFile;
36 import com.google.javascript.rhino.jstype.StaticSymbolTable;
37
38 import java.io.PrintStream;
39 import java.util.ArrayList;
40 import java.util.Collections;
41 import java.util.HashMap;
42 import java.util.List;
43 import java.util.Map;
44 import java.util.Set;
45
46 /**
47 * Builds a global namespace of all the objects and their properties in
48 * the global scope. Also builds an index of all the references to those names.
49 *
50 */
51 class GlobalNamespace
52 implements StaticScope<JSType>,
53 StaticSymbolTable<GlobalNamespace.Name, GlobalNamespace.Ref> {
54
55 private AbstractCompiler compiler;
56 private final Node root;
57 private final Node externsRoot;
58 private boolean inExterns;
59 private Scope externsScope;
60 private boolean generated = false;
61
62 /**
63 * Each reference has an index in post-order.
64 * Notice that some nodes are represented by 2 Ref objects, so
65 * this index is not necessarily unique.
66 */
67 private int currentPreOrderIndex = 0;
68
69 /** Global namespace tree */
70 private List<Name> globalNames = new ArrayList<Name>();
71
72 /** Maps names (e.g. "a.b.c") to nodes in the global namespace tree */
73 private Map<String, Name> nameMap = new HashMap<String, Name>();
74
75 /**
76 * Creates an instance that may emit warnings when building the namespace.
77 *
78 * @param compiler The AbstractCompiler, for reporting code changes
79 * @param root The root of the rest of the code to build a namespace for.
80 */
81 GlobalNamespace(AbstractCompiler compiler, Node root) {
82 this(compiler, null, root);
83 }
84
85 /**
86 * Creates an instance that may emit warnings when building the namespace.
87 *
88 * @param compiler The AbstractCompiler, for reporting code changes
89 * @param externsRoot The root of the externs to build a namespace for. If
90 * this is null, externs and properties defined on extern types will not
91 * be included in the global namespace. If non-null, it allows
92 * user-defined function on extern types to be included in the global
93 * namespace. E.g. String.foo.
94 * @param root The root of the rest of the code to build a namespace for.
95 */
96 GlobalNamespace(AbstractCompiler compiler, Node externsRoot, Node root) {
97 this.compiler = compiler;
98 this.externsRoot = externsRoot;
99 this.root = root;
100 }
101
102 boolean hasExternsRoot() {
103 return externsRoot != null;
104 }
105
106 @Override
107 public Node getRootNode() {
108 return root.getParent();
109 }
110
111 @Override
112 public StaticScope<JSType> getParentScope() {
113 return null;
114 }
115
116 @Override
117 public Name getSlot(String name) {
118 return getOwnSlot(name);
119 }
120
121 @Override
122 public Name getOwnSlot(String name) {
123 ensureGenerated();
124 return nameMap.get(name);
125 }
126
127 @Override
128 public JSType getTypeOfThis() {
129 return compiler.getTypeRegistry().getNativeObjectType(GLOBAL_THIS);
130 }
131
132 @Override
133 public Iterable<Ref> getReferences(Name slot) {
134 ensureGenerated();
135 return Collections.unmodifiableList(slot.getRefs());
136 }
137
138 @Override
139 public StaticScope<JSType> getScope(Name slot) {
140 return this;
141 }
142
143 @Override
144 public Iterable<Name> getAllSymbols() {
145 ensureGenerated();
146 return Collections.unmodifiableCollection(getNameIndex().values());
147 }
148
149 private void ensureGenerated() {
150 if (!generated) {
151 process();
152 }
153 }
154
155 /**
156 * Gets a list of the roots of the forest of the global names, where the
157 * roots are the top-level names.
158 */
159 List<Name> getNameForest() {
160 ensureGenerated();
161 return globalNames;
162 }
163
164 /**
165 * Gets an index of all the global names, indexed by full qualified name
166 * (as in "a", "a.b.c", etc.).
167 */
168 Map<String, Name> getNameIndex() {
169 ensureGenerated();
170 return nameMap;
171 }
172
173 /**
174 * If the client adds new nodes to the AST, scan these new nodes
175 * to see if they've added any references to the global namespace.
176 * @param scope The scope to scan.
177 * @param newNodes New nodes to check.
178 */
179 void scanNewNodes(Scope scope, Set<Node> newNodes) {
180 NodeTraversal t = new NodeTraversal(compiler,
181 new BuildGlobalNamespace(new NodeFilter(newNodes)));
182 t.traverseAtScope(scope);
183 }
184
185 /**
186 * A filter that looks for qualified names that contain one of the nodes
187 * in the given set.
188 */
189 private static class NodeFilter implements Predicate<Node> {
190 private final Set<Node> newNodes;
191
192 NodeFilter(Set<Node> newNodes) {
193 this.newNodes = newNodes;
194 }
195
196 @Override
197 public boolean apply(Node n) {
198 if (!n.isQualifiedName()) {
199 return false;
200 }
201
202 Node current;
203 for (current = n;
204 current.isGetProp();
205 current = current.getFirstChild()) {
206 if (newNodes.contains(current)) {
207 return true;
208 }
209 }
210
211 return current.isName() && newNodes.contains(current);
212 }
213 }
214
215 /**
216 * Builds the namespace lazily.
217 */
218 private void process() {
219 if (externsRoot != null) {
220 inExterns = true;
221 NodeTraversal.traverse(compiler, externsRoot, new BuildGlobalNamespace());
222 }
223 inExterns = false;
224
225 NodeTraversal.traverse(compiler, root, new BuildGlobalNamespace());
226 generated = true;
227 }
228
229 /**
230 * Determines whether a name reference in a particular scope is a global name
231 * reference.
232 *
233 * @param name A variable or property name (e.g. "a" or "a.b.c.d")
234 * @param s The scope in which the name is referenced
235 * @return Whether the name reference is a global name reference
236 */
237 private boolean isGlobalNameReference(String name, Scope s) {
238 String topVarName = getTopVarName(name);
239 return isGlobalVarReference(topVarName, s);
240 }
241
242 /**
243 * Gets the top variable name from a possibly namespaced name.
244 *
245 * @param name A variable or qualified property name (e.g. "a" or "a.b.c.d")
246 * @return The top variable name (e.g. "a")
247 */
248 private String getTopVarName(String name) {
249 int firstDotIndex = name.indexOf('.');
250 return firstDotIndex == -1 ? name : name.substring(0, firstDotIndex);
251 }
252
253 /**
254 * Determines whether a variable name reference in a particular scope is a
255 * global variable reference.
256 *
257 * @param name A variable name (e.g. "a")
258 * @param s The scope in which the name is referenced
259 * @return Whether the name reference is a global variable reference
260 */
261 private boolean isGlobalVarReference(String name, Scope s) {
262 Scope.Var v = s.getVar(name);
263 if (v == null && externsScope != null) {
264 v = externsScope.getVar(name);
265 }
266 return v != null && !v.isLocal();
267 }
268
269 /**
270 * Gets whether a scope is the global scope.
271 *
272 * @param s A scope
273 * @return Whether the scope is the global scope
274 */
275 private boolean isGlobalScope(Scope s) {
276 return s.getParent() == null;
277 }
278
279 // -------------------------------------------------------------------------
280
281 /**
282 * Builds a tree representation of the global namespace. Omits prototypes.
283 */
284 private class BuildGlobalNamespace implements NodeTraversal.Callback {
285
286 private final Predicate<Node> nodeFilter;
287
288 BuildGlobalNamespace() {
289 this(null);
290 }
291
292 /**
293 * Builds a global namespace, but only visits nodes that match the
294 * given filter.
295 */
296 BuildGlobalNamespace(Predicate<Node> nodeFilter) {
297 this.nodeFilter = nodeFilter;
298 }
299
300 @Override
301 public void visit(NodeTraversal t, Node n, Node parent) {}
302
303 /** Collect the references in pre-order. */
304 @Override
305 public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
306 collect(t, n, parent);
307 return true;
308 }
309
310 public void collect(NodeTraversal t, Node n, Node parent) {
311 if (nodeFilter != null && !nodeFilter.apply(n)) {
312 return;
313 }
314
315 // If we are traversing the externs, then we save a pointer to the scope
316 // generated by them, so that we can do lookups in it later.
317 if (externsRoot != null && n == externsRoot) {
318 externsScope = t.getScope();
319 }
320
321 String name;
322 boolean isSet = false;
323 Name.Type type = Name.Type.OTHER;
324 boolean isPropAssign = false;
325
326 switch (n.getType()) {
327 case Token.GETTER_DEF:
328 case Token.SETTER_DEF:
329 case Token.STRING_KEY:
330 // This may be a key in an object literal declaration.
331 name = null;
332 if (parent != null && parent.isObjectLit()) {
333 name = getNameForObjLitKey(n);
334 }
335 if (name == null) return;
336 isSet = true;
337 switch (n.getType()) {
338 case Token.STRING_KEY:
339 type = getValueType(n.getFirstChild());
340 break;
341 case Token.GETTER_DEF:
342 type = Name.Type.GET;
343 break;
344 case Token.SETTER_DEF:
345 type = Name.Type.SET;
346 break;
347 default:
348 throw new IllegalStateException("unexpected:" + n);
349 }
350 break;
351 case Token.NAME:
352 // This may be a variable get or set.
353 if (parent != null) {
354 switch (parent.getType()) {
355 case Token.VAR:
356 isSet = true;
357 Node rvalue = n.getFirstChild();
358 type = rvalue == null ? Name.Type.OTHER : getValueType(rvalue);
359 break;
360 case Token.ASSIGN:
361 if (parent.getFirstChild() == n) {
362 isSet = true;
363 type = getValueType(n.getNext());
364 }
365 break;
366 case Token.GETPROP:
367 return;
368 case Token.FUNCTION:
369 Node gramps = parent.getParent();
370 if (gramps == null ||
371 NodeUtil.isFunctionExpression(parent)) return;
372 isSet = true;
373 type = Name.Type.FUNCTION;
374 break;
375 case Token.INC:
376 case Token.DEC:
377 isSet = true;
378 type = Name.Type.OTHER;
379 break;
380 default:
381 if (NodeUtil.isAssignmentOp(parent) &&
382 parent.getFirstChild() == n) {
383 isSet = true;
384 type = Name.Type.OTHER;
385 }
386 }
387 }
388 name = n.getString();
389 break;
390 case Token.GETPROP:
391 // This may be a namespaced name get or set.
392 if (parent != null) {
393 switch (parent.getType()) {
394 case Token.ASSIGN:
395 if (parent.getFirstChild() == n) {
396 isSet = true;
397 type = getValueType(n.getNext());
398 isPropAssign = true;
399 }
400 break;
401 case Token.INC:
402 case Token.DEC:
403 isSet = true;
404 type = Name.Type.OTHER;
405 break;
406 case Token.GETPROP:
407 return;
408 default:
409 if (NodeUtil.isAssignmentOp(parent) &&
410 parent.getFirstChild() == n) {
411 isSet = true;
412 type = Name.Type.OTHER;
413 }
414 }
415 }
416 name = n.getQualifiedName();
417 if (name == null) return;
418 break;
419 default:
420 return;
421 }
422
423 // We are only interested in global names.
424 Scope scope = t.getScope();
425 if (!isGlobalNameReference(name, scope)) {
426 return;
427 }
428
429 if (isSet) {
430 if (isGlobalScope(scope)) {
431 handleSetFromGlobal(t, n, parent, name, isPropAssign, type);
432 } else {
433 handleSetFromLocal(t, n, parent, name);
434 }
435 } else {
436 handleGet(t, n, parent, name);
437 }
438 }
439
440 /**
441 * Gets the fully qualified name corresponding to an object literal key,
442 * as long as it and its prefix property names are valid JavaScript
443 * identifiers. The object literal may be nested inside of other object
444 * literals.
445 *
446 * For example, if called with node {@code n} representing "z" in any of
447 * the following expressions, the result would be "w.x.y.z":
448 * <code> var w = {x: {y: {z: 0}}}; </code>
449 * <code> w.x = {y: {z: 0}}; </code>
450 * <code> w.x.y = {'a': 0, 'z': 0}; </code>
451 *
452 * @param n A child of an OBJLIT node
453 * @return The global name, or null if {@code n} doesn't correspond to the
454 * key of an object literal that can be named
455 */
456 String getNameForObjLitKey(Node n) {
457 Node parent = n.getParent();
458 Preconditions.checkState(parent.isObjectLit());
459
460 Node gramps = parent.getParent();
461 if (gramps == null) {
462 return null;
463 }
464
465 Node greatGramps = gramps.getParent();
466 String name;
467 switch (gramps.getType()) {
468 case Token.NAME:
469 // VAR
470 // NAME (gramps)
471 // OBJLIT (parent)
472 // STRING (n)
473 if (greatGramps == null || !greatGramps.isVar()) {
474 return null;
475 }
476 name = gramps.getString();
477 break;
478 case Token.ASSIGN:
479 // ASSIGN (gramps)
480 // NAME|GETPROP
481 // OBJLIT (parent)
482 // STRING (n)
483 Node lvalue = gramps.getFirstChild();
484 name = lvalue.getQualifiedName();
485 break;
486 case Token.STRING_KEY:
487 // OBJLIT
488 // STRING (gramps)
489 // OBJLIT (parent)
490 // STRING (n)
491 if (greatGramps != null &&
492 greatGramps.isObjectLit()) {
493 name = getNameForObjLitKey(gramps);
494 } else {
495 return null;
496 }
497 break;
498 default:
499 return null;
500 }
501 if (name != null) {
502 String key = n.getString();
503 if (TokenStream.isJSIdentifier(key)) {
504 return name + '.' + key;
505 }
506 }
507 return null;
508 }
509
510 /**
511 * Gets the type of a value or simple expression.
512 *
513 * @param n An r-value in an assignment or variable declaration (not null)
514 * @return A {@link Name.Type}
515 */
516 Name.Type getValueType(Node n) {
517 switch (n.getType()) {
518 case Token.OBJECTLIT:
519 return Name.Type.OBJECTLIT;
520 case Token.FUNCTION:
521 return Name.Type.FUNCTION;
522 case Token.OR:
523 // Recurse on the second value. If the first value were an object
524 // literal or function, then the OR would be meaningless and the
525 // second value would be dead code. Assume that if the second value
526 // is an object literal or function, then the first value will also
527 // evaluate to one when it doesn't evaluate to false.
528 return getValueType(n.getLastChild());
529 case Token.HOOK:
530 // The same line of reasoning used for the OR case applies here.
531 Node second = n.getFirstChild().getNext();
532 Name.Type t = getValueType(second);
533 if (t != Name.Type.OTHER) return t;
534 Node third = second.getNext();
535 return getValueType(third);
536 }
537 return Name.Type.OTHER;
538 }
539
540 /**
541 * Updates our representation of the global namespace to reflect an
542 * assignment to a global name in global scope.
543 *
544 * @param t The traversal
545 * @param n The node currently being visited
546 * @param parent {@code n}'s parent
547 * @param name The global name (e.g. "a" or "a.b.c.d")
548 * @param isPropAssign Whether this set corresponds to a property
549 * assignment of the form <code>a.b.c = ...;</code>
550 * @param type The type of the value that the name is being assigned
551 */
552 void handleSetFromGlobal(NodeTraversal t, Node n, Node parent, String name,
553 boolean isPropAssign, Name.Type type) {
554 if (maybeHandlePrototypePrefix(t, n, parent, name)) return;
555
556 Name nameObj = getOrCreateName(name);
557 nameObj.type = type;
558
559 Ref set = new Ref(t, n, nameObj, Ref.Type.SET_FROM_GLOBAL,
560 currentPreOrderIndex++);
561 nameObj.addRef(set);
562
563 if (isNestedAssign(parent)) {
564 // This assignment is both a set and a get that creates an alias.
565 Ref get = new Ref(t, n, nameObj, Ref.Type.ALIASING_GET,
566 currentPreOrderIndex++);
567 nameObj.addRef(get);
568 Ref.markTwins(set, get);
569 } else if (isTypeDeclaration(n, parent)) {
570 // Names with a @constructor or @enum annotation are always collapsed
571 nameObj.setDeclaredType();
572 }
573 }
574
575 /**
576 * Determines whether a set operation is a constructor or enumeration
577 * or interface declaration. The set operation may either be an assignment
578 * to a name, a variable declaration, or an object literal key mapping.
579 *
580 * @param n The node that represents the name being set
581 * @param parent Parent node of {@code n} (an ASSIGN, VAR, or OBJLIT node)
582 * @return Whether the set operation is either a constructor or enum
583 * declaration
584 */
585 private boolean isTypeDeclaration(Node n, Node parent) {
586 Node valueNode = NodeUtil.getRValueOfLValue(n);
587 JSDocInfo info = NodeUtil.getBestJSDocInfo(n);
588 // Heed the annotations only if they're sensibly used.
589 return info != null && valueNode != null &&
590 (info.isConstructor() && valueNode.isFunction() ||
591 info.isInterface() && valueNode.isFunction() ||
592 info.hasEnumParameterType() && valueNode.isObjectLit());
593 }
594
595 /**
596 * Updates our representation of the global namespace to reflect an
597 * assignment to a global name in a local scope.
598 *
599 * @param t The traversal
600 * @param n The node currently being visited
601 * @param parent {@code n}'s parent
602 * @param name The global name (e.g. "a" or "a.b.c.d")
603 */
604 void handleSetFromLocal(NodeTraversal t, Node n, Node parent,
605 String name) {
606 if (maybeHandlePrototypePrefix(t, n, parent, name)) return;
607
608 Name nameObj = getOrCreateName(name);
609 Ref set = new Ref(t, n, nameObj,
610 Ref.Type.SET_FROM_LOCAL, currentPreOrderIndex++);
611 nameObj.addRef(set);
612
613 if (isNestedAssign(parent)) {
614 // This assignment is both a set and a get that creates an alias.
615 Ref get = new Ref(t, n, nameObj,
616 Ref.Type.ALIASING_GET, currentPreOrderIndex++);
617 nameObj.addRef(get);
618 Ref.markTwins(set, get);
619 }
620 }
621
622 /**
623 * Updates our representation of the global namespace to reflect a read
624 * of a global name.
625 *
626 * @param t The traversal
627 * @param n The node currently being visited
628 * @param parent {@code n}'s parent
629 * @param name The global name (e.g. "a" or "a.b.c.d")
630 */
631 void handleGet(NodeTraversal t, Node n, Node parent, String name) {
632 if (maybeHandlePrototypePrefix(t, n, parent, name)) return;
633
634 Ref.Type type = Ref.Type.DIRECT_GET;
635 if (parent != null) {
636 switch (parent.getType()) {
637 case Token.IF:
638 case Token.TYPEOF:
639 case Token.VOID:
640 case Token.NOT:
641 case Token.BITNOT:
642 case Token.POS:
643 case Token.NEG:
644 break;
645 case Token.CALL:
646 type = n == parent.getFirstChild()
647 ? Ref.Type.CALL_GET
648 : Ref.Type.ALIASING_GET;
649 break;
650 case Token.NEW:
651 type = n == parent.getFirstChild()
652 ? Ref.Type.DIRECT_GET
653 : Ref.Type.ALIASING_GET;
654 break;
655 case Token.OR:
656 case Token.AND:
657 // This node is x or y in (x||y) or (x&&y). We only know that an
658 // alias is not getting created for this name if the result is used
659 // in a boolean context or assigned to the same name
660 // (e.g. var a = a || {}).
661 type = determineGetTypeForHookOrBooleanExpr(t, parent, name);
662 break;
663 case Token.HOOK:
664 if (n != parent.getFirstChild()) {
665 // This node is y or z in (x?y:z). We only know that an alias is
666 // not getting created for this name if the result is assigned to
667 // the same name (e.g. var a = a ? a : {}).
668 type = determineGetTypeForHookOrBooleanExpr(t, parent, name);
669 }
670 break;
671 case Token.DELPROP:
672 type = Ref.Type.DELETE_PROP;
673 break;
674 default:
675 type = Ref.Type.ALIASING_GET;
676 break;
677 }
678 }
679
680 handleGet(t, n, parent, name, type);
681 }
682
683 /**
684 * Determines whether the result of a hook (x?y:z) or boolean expression
685 * (x||y) or (x&&y) is assigned to a specific global name.
686 *
687 * @param t The traversal
688 * @param parent The parent of the current node in the traversal. This node
689 * should already be known to be a HOOK, AND, or OR node.
690 * @param name A name that is already known to be global in the current
691 * scope (e.g. "a" or "a.b.c.d")
692 * @return The expression's get type, either {@link Ref.Type#DIRECT_GET} or
693 * {@link Ref.Type#ALIASING_GET}
694 */
695 Ref.Type determineGetTypeForHookOrBooleanExpr(
696 NodeTraversal t, Node parent, String name) {
697 Node prev = parent;
698 for (Node anc : parent.getAncestors()) {
699 switch (anc.getType()) {
700 case Token.EXPR_RESULT:
701 case Token.VAR:
702 case Token.IF:
703 case Token.WHILE:
704 case Token.FOR:
705 case Token.TYPEOF:
706 case Token.VOID:
707 case Token.NOT:
708 case Token.BITNOT:
709 case Token.POS:
710 case Token.NEG:
711 return Ref.Type.DIRECT_GET;
712 case Token.HOOK:
713 if (anc.getFirstChild() == prev) {
714 return Ref.Type.DIRECT_GET;
715 }
716 break;
717 case Token.ASSIGN:
718 if (!name.equals(anc.getFirstChild().getQualifiedName())) {
719 return Ref.Type.ALIASING_GET;
720 }
721 break;
722 case Token.NAME: // a variable declaration
723 if (!name.equals(anc.getString())) {
724 return Ref.Type.ALIASING_GET;
725 }
726 break;
727 case Token.CALL:
728 if (anc.getFirstChild() != prev) {
729 return Ref.Type.ALIASING_GET;
730 }
731 break;
732 case Token.DELPROP:
733 return Ref.Type.DELETE_PROP;
734 }
735 prev = anc;
736 }
737 return Ref.Type.ALIASING_GET;
738 }
739
740 /**
741 * Updates our representation of the global namespace to reflect a read
742 * of a global name.
743 *
744 * @param t The current node traversal
745 * @param n The node currently being visited
746 * @param parent {@code n}'s parent
747 * @param name The global name (e.g. "a" or "a.b.c.d")
748 * @param type The reference type
749 */
750 void handleGet(NodeTraversal t, Node n, Node parent,
751 String name, Ref.Type type) {
752 Name nameObj = getOrCreateName(name);
753
754 // No need to look up additional ancestors, since they won't be used.
755 nameObj.addRef(new Ref(t, n, nameObj, type, currentPreOrderIndex++));
756 }
757
758 /**
759 * Updates our representation of the global namespace to reflect a read
760 * of a global name's longest prefix before the "prototype" property if the
761 * name includes the "prototype" property. Does nothing otherwise.
762 *
763 * @param t The current node traversal
764 * @param n The node currently being visited
765 * @param parent {@code n}'s parent
766 * @param name The global name (e.g. "a" or "a.b.c.d")
767 * @return Whether the name was handled
768 */
769 boolean maybeHandlePrototypePrefix(NodeTraversal t, Node n, Node parent,
770 String name) {
771 // We use a string-based approach instead of inspecting the parse tree
772 // to avoid complexities with object literals, possibly nested, beneath
773 // assignments.
774
775 int numLevelsToRemove;
776 String prefix;
777 if (name.endsWith(".prototype")) {
778 numLevelsToRemove = 1;
779 prefix = name.substring(0, name.length() - 10);
780 } else {
781 int i = name.indexOf(".prototype.");
782 if (i == -1) {
783 return false;
784 }
785 prefix = name.substring(0, i);
786 numLevelsToRemove = 2;
787 i = name.indexOf('.', i + 11);
788 while (i >= 0) {
789 numLevelsToRemove++;
790 i = name.indexOf('.', i + 1);
791 }
792 }
793
794 if (parent != null && NodeUtil.isObjectLitKey(n)) {
795 // Object literal keys have no prefix that's referenced directly per
796 // key, so we're done.
797 return true;
798 }
799
800 for (int i = 0; i < numLevelsToRemove; i++) {
801 parent = n;
802 n = n.getFirstChild();
803 }
804
805 handleGet(t, n, parent, prefix, Ref.Type.PROTOTYPE_GET);
806 return true;
807 }
808
809 /**
810 * Determines whether an assignment is nested (i.e. whether its return
811 * value is used).
812 *
813 * @param parent The parent of the current traversal node (not null)
814 * @return Whether it appears that the return value of the assignment is
815 * used
816 */
817 boolean isNestedAssign(Node parent) {
818 return parent.isAssign() &&
819 !parent.getParent().isExprResult();
820 }
821
822 /**
823 * Gets a {@link Name} instance for a global name. Creates it if necessary,
824 * as well as instances for any of its prefixes that are not yet defined.
825 *
826 * @param name A global name (e.g. "a", "a.b.c.d")
827 * @return The {@link Name} instance for {@code name}
828 */
829 Name getOrCreateName(String name) {
830 Name node = nameMap.get(name);
831 if (node == null) {
832 int i = name.lastIndexOf('.');
833 if (i >= 0) {
834 String parentName = name.substring(0, i);
835 Name parent = getOrCreateName(parentName);
836 node = parent.addProperty(name.substring(i + 1), inExterns);
837 } else {
838 node = new Name(name, null, inExterns);
839 globalNames.add(node);
840 }
841 nameMap.put(name, node);
842 }
843 return node;
844 }
845 }
846
847 // -------------------------------------------------------------------------
848
849 /**
850 * A name defined in global scope (e.g. "a" or "a.b.c.d"). These form a tree.
851 * As the parse tree traversal proceeds, we'll discover that some names
852 * correspond to JavaScript objects whose properties we should consider
853 * collapsing.
854 */
855 static class Name implements StaticSlot<JSType> {
856 enum Type {
857 OBJECTLIT,
858 FUNCTION,
859 GET,
860 SET,
861 OTHER,
862 }
863
864 private final String baseName;
865 final Name parent;
866 List<Name> props;
867
868 /** The first global assignment to a name. */
869 private Ref declaration;
870
871 /** All references to a name. This must contain {@code declaration}. */
872 private List<Ref> refs;
873
874 Type type;
875 private boolean declaredType = false;
876 private boolean hasDeclaredTypeDescendant = false;
877 int globalSets = 0;
878 int localSets = 0;
879 int aliasingGets = 0;
880 int totalGets = 0;
881 int callGets = 0;
882 int deleteProps = 0;
883 final boolean inExterns;
884
885 JSDocInfo docInfo = null;
886
887 Name(String name, Name parent, boolean inExterns) {
888 this.baseName = name;
889 this.parent = parent;
890 this.type = Type.OTHER;
891 this.inExterns = inExterns;
892 }
893
894 Name addProperty(String name, boolean inExterns) {
895 if (props == null) {
896 props = new ArrayList<Name>();
897 }
898 Name node = new Name(name, this, inExterns);
899 props.add(node);
900 return node;
901 }
902
903 String getBaseName() {
904 return baseName;
905 }
906
907 @Override
908 public String getName() {
909 return getFullName();
910 }
911
912 String getFullName() {
913 return parent == null ? baseName : parent.getFullName() + '.' + baseName;
914 }
915
916 @Override
917 public Ref getDeclaration() {
918 return declaration;
919 }
920
921 @Override
922 public boolean isTypeInferred() {
923 return false;
924 }
925
926 @Override
927 public JSType getType() {
928 return null;
929 }
930
931 void addRef(Ref ref) {
932 addRefInternal(ref);
933 switch (ref.type) {
934 case SET_FROM_GLOBAL:
935 if (declaration == null) {
936 declaration = ref;
937 docInfo = getDocInfoForDeclaration(ref);
938 }
939 globalSets++;
940 break;
941 case SET_FROM_LOCAL:
942 localSets++;
943 break;
944 case PROTOTYPE_GET:
945 case DIRECT_GET:
946 totalGets++;
947 break;
948 case ALIASING_GET:
949 aliasingGets++;
950 totalGets++;
951 break;
952 case CALL_GET:
953 callGets++;
954 totalGets++;
955 break;
956 case DELETE_PROP:
957 deleteProps++;
958 break;
959 default:
960 throw new IllegalStateException();
961 }
962 }
963
964 void removeRef(Ref ref) {
965 if (refs != null && refs.remove(ref)) {
966 if (ref == declaration) {
967 declaration = null;
968 if (refs != null) {
969 for (Ref maybeNewDecl : refs) {
970 if (maybeNewDecl.type == Ref.Type.SET_FROM_GLOBAL) {
971 declaration = maybeNewDecl;
972 break;
973 }
974 }
975 }
976 }
977
978 switch (ref.type) {
979 case SET_FROM_GLOBAL:
980 globalSets--;
981 break;
982 case SET_FROM_LOCAL:
983 localSets--;
984 break;
985 case PROTOTYPE_GET:
986 case DIRECT_GET:
987 totalGets--;
988 break;
989 case ALIASING_GET:
990 aliasingGets--;
991 totalGets--;
992 break;
993 case CALL_GET:
994 callGets--;
995 totalGets--;
996 break;
997 case DELETE_PROP:
998 deleteProps--;
999 break;
1000 default:
1001 throw new IllegalStateException();
1002 }
1003 }
1004 }
1005
1006 List<Ref> getRefs() {
1007 return refs == null ? ImmutableList.<Ref>of() : refs;
1008 }
1009
1010 void addRefInternal(Ref ref) {
1011 if (refs == null) {
1012 refs = Lists.newArrayList();
1013 }
1014 refs.add(ref);
1015 }
1016
1017 boolean canEliminate() {
1018 if (!canCollapseUnannotatedChildNames() || totalGets > 0) {
1019 return false;
1020 }
1021
1022 if (props != null) {
1023 for (Name n : props) {
1024 if (!n.canCollapse()) {
1025 return false;
1026 }
1027 }
1028 }
1029 return true;
1030 }
1031
1032 boolean isSimpleStubDeclaration() {
1033 if (getRefs().size() == 1) {
1034 Ref ref = refs.get(0);
1035 if (ref.node.getParent() != null &&
1036 ref.node.getParent().isExprResult()) {
1037 return true;
1038 }
1039 }
1040 return false;
1041 }
1042
1043 boolean canCollapse() {
1044 return !inExterns && !isGetOrSetDefinition() && (declaredType ||
1045 (parent == null || parent.canCollapseUnannotatedChildNames()) &&
1046 (globalSets > 0 || localSets > 0) &&
1047 deleteProps == 0);
1048 }
1049
1050 boolean isGetOrSetDefinition() {
1051 return this.type == Type.GET || this.type == Type.SET;
1052 }
1053
1054 boolean canCollapseUnannotatedChildNames() {
1055 if (type == Type.OTHER || isGetOrSetDefinition()
1056 || globalSets != 1 || localSets != 0 || deleteProps != 0) {
1057 return false;
1058 }
1059
1060 // Don't try to collapse if the one global set is a twin reference.
1061 // We could theoretically handle this case in CollapseProperties, but
1062 // it's probably not worth the effort.
1063 Preconditions.checkNotNull(declaration);
1064 if (declaration.getTwin() != null) {
1065 return false;
1066 }
1067
1068 if (declaredType) {
1069 return true;
1070 }
1071
1072 // If this is a key of an aliased object literal, then it will be aliased
1073 // later. So we won't be able to collapse its properties.
1074 if (parent != null && parent.shouldKeepKeys()) {
1075 return false;
1076 }
1077
1078 // If this is aliased, then its properties can't be collapsed either.
1079 if (aliasingGets > 0) {
1080 return false;
1081 }
1082
1083 return (parent == null || parent.canCollapseUnannotatedChildNames());
1084 }
1085
1086 /** Whether this is an object literal that needs to keep its keys. */
1087 boolean shouldKeepKeys() {
1088 return type == Type.OBJECTLIT && aliasingGets > 0;
1089 }
1090
1091 boolean needsToBeStubbed() {
1092 return globalSets == 0 && localSets > 0;
1093 }
1094
1095 void setDeclaredType() {
1096 declaredType = true;
1097 for (Name ancestor = parent; ancestor != null;
1098 ancestor = ancestor.parent) {
1099 ancestor.hasDeclaredTypeDescendant = true;
1100 }
1101 }
1102
1103 boolean isDeclaredType() {
1104 return declaredType;
1105 }
1106
1107 /**
1108 * Determines whether this name is a prefix of at least one class or enum
1109 * name. Because classes and enums are always collapsed, the namespace will
1110 * have different properties in compiled code than in uncompiled code.
1111 *
1112 * For example, if foo.bar.DomHelper is a class, then foo and foo.bar are
1113 * considered namespaces.
1114 */
1115 boolean isNamespace() {
1116 return hasDeclaredTypeDescendant && type == Type.OBJECTLIT;
1117 }
1118
1119 /**
1120 * Determines whether this is a simple name (as opposed to a qualified
1121 * name).
1122 */
1123 boolean isSimpleName() {
1124 return parent == null;
1125 }
1126
1127 @Override public String toString() {
1128 return getFullName() + " (" + type + "): globalSets=" + globalSets +
1129 ", localSets=" + localSets + ", totalGets=" + totalGets +
1130 ", aliasingGets=" + aliasingGets + ", callGets=" + callGets;
1131 }
1132
1133 @Override
1134 public JSDocInfo getJSDocInfo() {
1135 return docInfo;
1136 }
1137
1138 /**
1139 * Tries to get the doc info for a given declaration ref.
1140 */
1141 private static JSDocInfo getDocInfoForDeclaration(Ref ref) {
1142 if (ref.node != null) {
1143 Node refParent = ref.node.getParent();
1144 switch (refParent.getType()) {
1145 case Token.FUNCTION:
1146 case Token.ASSIGN:
1147 return refParent.getJSDocInfo();
1148 case Token.VAR:
1149 return ref.node == refParent.getFirstChild() ?
1150 refParent.getJSDocInfo() : ref.node.getJSDocInfo();
1151 }
1152 }
1153
1154 return null;
1155 }
1156 }
1157
1158 // -------------------------------------------------------------------------
1159
1160 /**
1161 * A global name reference. Contains references to the relevant parse tree
1162 * node and its ancestors that may be affected.
1163 */
1164 static class Ref implements StaticReference<JSType> {
1165 enum Type {
1166 SET_FROM_GLOBAL,
1167 SET_FROM_LOCAL,
1168 PROTOTYPE_GET,
1169 ALIASING_GET, // Prevents a name's properties from being collapsed
1170 DIRECT_GET, // Prevents a name from being completely eliminated
1171 CALL_GET, // Prevents a name from being collapsed if never set
1172 DELETE_PROP, // Prevents a name from being collapsed at all.
1173 }
1174
1175 Node node;
1176 final JSModule module;
1177 final StaticSourceFile source;
1178 final Name name;
1179 final Type type;
1180 final Scope scope;
1181 final int preOrderIndex;
1182
1183 /**
1184 * Certain types of references are actually double-refs. For example,
1185 * var a = b = 0;
1186 * counts as both a "set" of b and an "alias" of b.
1187 *
1188 * We create two Refs for this node, and mark them as twins of each other.
1189 */
1190 private Ref twin = null;
1191
1192 /**
1193 * Creates a reference at the current node.
1194 */
1195 Ref(NodeTraversal t, Node node, Name name, Type type, int index) {
1196 this.node = node;
1197 this.name = name;
1198 this.module = t.getInput() == null ? null : t.getInput().getModule();
1199 this.source = node.getStaticSourceFile();
1200 this.type = type;
1201 this.scope = t.getScope();
1202 this.preOrderIndex = index;
1203 }
1204
1205 private Ref(Ref original, Type type, int index) {
1206 this.node = original.node;
1207 this.name = original.name;
1208 this.module = original.module;
1209 this.source = original.source;
1210 this.type = type;
1211 this.scope = original.scope;
1212 this.preOrderIndex = index;
1213 }
1214
1215 private Ref(Type type, int index) {
1216 this.type = type;
1217 this.module = null;
1218 this.source = null;
1219 this.scope = null;
1220 this.name = null;
1221 this.preOrderIndex = index;
1222 }
1223
1224 @Override
1225 public Node getNode() {
1226 return node;
1227 }
1228
1229 @Override
1230 public StaticSourceFile getSourceFile() {
1231 return source;
1232 }
1233
1234 @Override
1235 public StaticSlot<JSType> getSymbol() {
1236 return name;
1237 }
1238
1239 JSModule getModule() {
1240 return module;
1241 }
1242
1243 String getSourceName() {
1244 return source == null ? "" : source.getName();
1245 }
1246
1247 Ref getTwin() {
1248 return twin;
1249 }
1250
1251 boolean isSet() {
1252 return type == Type.SET_FROM_GLOBAL || type == Type.SET_FROM_LOCAL;
1253 }
1254
1255 static void markTwins(Ref a, Ref b) {
1256 Preconditions.checkArgument(
1257 (a.type == Type.ALIASING_GET || b.type == Type.ALIASING_GET) &&
1258 (a.type == Type.SET_FROM_GLOBAL || a.type == Type.SET_FROM_LOCAL ||
1259 b.type == Type.SET_FROM_GLOBAL || b.type == Type.SET_FROM_LOCAL));
1260 a.twin = b;
1261 b.twin = a;
1262 }
1263
1264 /**
1265 * Create a new ref that is the same as this one, but of
1266 * a different class.
1267 */
1268 Ref cloneAndReclassify(Type type) {
1269 return new Ref(this, type, this.preOrderIndex);
1270 }
1271
1272 static Ref createRefForTesting(Type type) {
1273 return new Ref(type, -1);
1274 }
1275 }
1276
1277
1278 /**
1279 * An experimental compiler pass for tracking what symbols were added/removed
1280 * at each stage of compilation.
1281 *
1282 * When "global namespace tracker" mode is on, we rebuild the global namespace
1283 * after each pass, and diff it against the last namespace built.
1284 */
1285 static class Tracker implements CompilerPass {
1286 private final AbstractCompiler compiler;
1287 private final PrintStream stream;
1288 private final Predicate<String> isInterestingSymbol;
1289
1290 private Set<String> previousSymbolsInTree = ImmutableSet.of();
1291
1292 /**
1293 @param stream The stream to print logs to.
1294 * @param isInterestingSymbol A predicate to determine which symbols
1295 * we care about.
1296 */
1297 Tracker(AbstractCompiler compiler, PrintStream stream,
1298 Predicate<String> isInterestingSymbol) {
1299 this.compiler = compiler;
1300 this.stream = stream;
1301 this.isInterestingSymbol = isInterestingSymbol;
1302 }
1303
1304 @Override public void process(Node externs, Node root) {
1305 GlobalNamespace namespace = new GlobalNamespace(compiler, externs, root);
1306
1307 Set<String> currentSymbols = Sets.newTreeSet();
1308 for (String name : namespace.getNameIndex().keySet()) {
1309 if (isInterestingSymbol.apply(name)) {
1310 currentSymbols.add(name);
1311 }
1312 }
1313
1314 String passName = compiler.getLastPassName();
1315 if (passName == null) {
1316 passName = "[Unknown pass]";
1317 }
1318
1319 for (String sym : currentSymbols) {
1320 if (!previousSymbolsInTree.contains(sym)) {
1321 stream.println(String.format("%s: Added by %s", sym, passName));
1322 }
1323 }
1324
1325 for (String sym : previousSymbolsInTree) {
1326 if (!currentSymbols.contains(sym)) {
1327 stream.println(String.format("%s: Removed by %s", sym, passName));
1328 }
1329 }
1330
1331 previousSymbolsInTree = currentSymbols;
1332 }
1333 }
1334 }