Debian Codegraph @

src/com/google/javascript/jscomp/SymbolTable.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.Predicates;
21 import com.google.common.collect.HashBasedTable;
22 import com.google.common.collect.ImmutableList;
23 import com.google.common.collect.Iterables;
24 import com.google.common.collect.Lists;
25 import com.google.common.collect.Maps;
26 import com.google.common.collect.Ordering;
27 import com.google.common.collect.Sets;
28 import com.google.common.collect.Table;
29 import com.google.javascript.rhino.JSDocInfo;
30 import com.google.javascript.rhino.JSDocInfo.Marker;
31 import com.google.javascript.rhino.Node;
32 import com.google.javascript.rhino.SourcePosition;
33 import com.google.javascript.rhino.jstype.EnumType;
34 import com.google.javascript.rhino.jstype.FunctionType;
35 import com.google.javascript.rhino.jstype.JSType;
36 import com.google.javascript.rhino.jstype.JSTypeNative;
37 import com.google.javascript.rhino.jstype.JSTypeRegistry;
38 import com.google.javascript.rhino.jstype.ObjectType;
39 import com.google.javascript.rhino.jstype.SimpleReference;
40 import com.google.javascript.rhino.jstype.SimpleSlot;
41 import com.google.javascript.rhino.jstype.StaticReference;
42 import com.google.javascript.rhino.jstype.StaticScope;
43 import com.google.javascript.rhino.jstype.StaticSlot;
44 import com.google.javascript.rhino.jstype.StaticSymbolTable;
45 import com.google.javascript.rhino.jstype.UnionType;
46
47 import java.util.Collection;
48 import java.util.Collections;
49 import java.util.List;
50 import java.util.Map;
51 import java.util.Set;
52 import java.util.TreeSet;
53 import java.util.logging.Logger;
54
55 import javax.annotation.Nullable;
56
57 /**
58 * A symbol table for people that want to use Closure Compiler as an indexer.
59 *
60 * Contains an index of all the symbols in the code within a compilation
61 * job. The API is designed for people who want to visit all the symbols, rather
62 * than people who want to lookup a specific symbol by a certain key.
63 *
64 * We can use this to combine different types of symbol tables. For example,
65 * one class might have a {@code StaticSymbolTable} of all variable references,
66 * and another class might have a {@code StaticSymbolTable} of all type names
67 * in JSDoc comments. This class allows you to combine them into a unified
68 * index.
69 *
70 * Most passes build their own "partial" symbol table that implements the same
71 * interface (StaticSymbolTable, StaticSlot, and friends). Individual compiler
72 * passes usually need more or less metadata about the certainty of symbol
73 * information. Building a complete symbol table with all the necessary metadata
74 * for all passes would be too slow. However, as long as these "partial" symbol
75 * tables implement the proper interfaces, we should be able to add them to this
76 * symbol table to make it more complete.
77 *
78 * If clients want fast lookup, they should build their own wrapper around
79 * this symbol table that indexes symbols or references by the desired lookup
80 * key.
81 *
82 * By design, when this symbol table creates symbols for types, it tries
83 * to mimic the symbol table you would get in an OO language. For example,
84 * the "type Foo" and "the constructor that creates objects of type Foo"
85 * are the same symbol. The types of "Foo.prototype" and "new Foo()" also
86 * have the same symbol. Although JSCompiler internally treats these as
87 * distinct symbols, we assume that most clients will not care about
88 * the distinction.
89 *
90 * @see #addSymbolsFrom For more information on how to write plugins for this
91 * symbol table.
92 *
93 * @author [email protected] (Nick Santos)
94 */
95 public final class SymbolTable
96 implements StaticSymbolTable<SymbolTable.Symbol, SymbolTable.Reference> {
97 private static final Logger logger =
98 Logger.getLogger(SymbolTable.class.getName());
99
100 /**
101 * The name we use for the JavaScript built-in Global object. It's
102 * anonymous in JavaScript, so we have to give it an invalid identifier
103 * to avoid conflicts with user-defined property names.
104 */
105 public static final String GLOBAL_THIS = "*global*";
106
107 /**
108 * All symbols in the program, uniquely identified by the node where
109 * they're declared and their name.
110 */
111 private final Table<Node, String, Symbol> symbols = HashBasedTable.create();
112
113 /**
114 * All syntactic scopes in the program, uniquely identified by the node where
115 * they're declared.
116 */
117 private final Map<Node, SymbolScope> scopes = Maps.newLinkedHashMap();
118
119 /**
120 * All JSDocInfo in the program.
121 */
122 private final List<JSDocInfo> docInfos = Lists.newArrayList();
123
124 private SymbolScope globalScope = null;
125
126 private final JSTypeRegistry registry;
127
128 /**
129 * Clients should get a symbol table by asking the compiler at the end
130 * of a compilation job.
131 */
132 SymbolTable(JSTypeRegistry registry) {
133 this.registry = registry;
134 }
135
136 @Override
137 public Iterable<Reference> getReferences(Symbol symbol) {
138 return Collections.unmodifiableCollection(symbol.references.values());
139 }
140
141 public List<Reference> getReferenceList(Symbol symbol) {
142 return ImmutableList.copyOf(symbol.references.values());
143 }
144
145 @Override
146 public Iterable<Symbol> getAllSymbols() {
147 return Collections.unmodifiableCollection(symbols.values());
148 }
149
150 /**
151 * Get the symbols in their natural ordering.
152 * Always returns a mutable list.
153 */
154 public List<Symbol> getAllSymbolsSorted() {
155 List<Symbol> sortedSymbols = Lists.newArrayList(symbols.values());
156 Collections.sort(sortedSymbols, getNaturalSymbolOrdering());
157 return sortedSymbols;
158 }
159
160 /**
161 * Gets the 'natural' ordering of symbols.
162 *
163 * Right now, we only guarantee that symbols in the global scope will come
164 * before symbols in local scopes. After that, the order is deterministic but
165 * undefined.
166 */
167 public Ordering<Symbol> getNaturalSymbolOrdering() {
168 return SYMBOL_ORDERING;
169 }
170
171 @Override
172 public SymbolScope getScope(Symbol slot) {
173 return slot.scope;
174 }
175
176 public Collection<JSDocInfo> getAllJSDocInfo() {
177 return Collections.unmodifiableList(docInfos);
178 }
179
180 /**
181 * Declare a symbol after the main symbol table was constructed.
182 * Throws an exception if you try to declare a symbol twice.
183 */
184 public Symbol declareInferredSymbol(
185 SymbolScope scope, String name, Node declNode) {
186 return declareSymbol(name, null, true, scope, declNode, null);
187 }
188
189 /**
190 * Gets the scope that contains the given node.
191 * If {@code n} is a function name, we return the scope that contains the
192 * function, not the function itself.
193 */
194 public SymbolScope getEnclosingScope(Node n) {
195 Node current = n.getParent();
196 if (n.isName() &&
197 n.getParent().isFunction()) {
198 current = current.getParent();
199 }
200
201 for (; current != null; current = current.getParent()) {
202 if (scopes.containsKey(current)) {
203 return scopes.get(current);
204 }
205 }
206 return null;
207 }
208
209 /**
210 * If {@code sym} is a function, try to find a Symbol for
211 * a parameter with the given name.
212 *
213 * Returns null if we couldn't find one.
214 *
215 * Notice that this just makes a best effort, and may not be able
216 * to find parameters for non-conventional function definitions.
217 * For example, we would not be able to find "y" in this code:
218 * <code>
219 * var x = x() ? function(y) {} : function(y) {};
220 * </code>
221 */
222 public Symbol getParameterInFunction(Symbol sym, String paramName) {
223 SymbolScope scope = getScopeInFunction(sym);
224 if (scope != null) {
225 Symbol param = scope.getSlot(paramName);
226 if (param != null && param.scope == scope) {
227 return param;
228 }
229 }
230 return null;
231 }
232
233 private SymbolScope getScopeInFunction(Symbol sym) {
234 FunctionType type = sym.getFunctionType();
235 if (type == null) {
236 return null;
237 }
238
239 Node functionNode = type.getSource();
240 if (functionNode == null) {
241 return null;
242 }
243
244 return scopes.get(functionNode);
245 }
246
247 /**
248 * All local scopes are associated with a function, and some functions
249 * are associated with a symbol. Returns the symbol associated with the given
250 * scope.
251 */
252 public Symbol getSymbolForScope(SymbolScope scope) {
253 if (scope.getSymbolForScope() == null) {
254 scope.setSymbolForScope(findSymbolForScope(scope));
255 }
256 return scope.getSymbolForScope();
257 }
258
259 /**
260 * Find the symbol associated with the given scope.
261 * Notice that we won't always be able to figure out this association
262 * dynamically, so sometimes we'll just create the association when we
263 * create the scope.
264 */
265 private Symbol findSymbolForScope(SymbolScope scope) {
266 Node rootNode = scope.getRootNode();
267 if (rootNode.getParent() == null) {
268 return globalScope.getSlot(GLOBAL_THIS);
269 }
270
271 if (!rootNode.isFunction()) {
272 return null;
273 }
274
275 String name = NodeUtil.getBestLValueName(
276 NodeUtil.getBestLValue(rootNode));
277 return name == null ? null : scope.getParentScope().getQualifiedSlot(name);
278 }
279
280 /**
281 * Get all symbols associated with the type of the given symbol.
282 *
283 * For example, given a variable x declared as
284 * /* @type {Array|Date} /
285 * var x = f();
286 * this will return the constructors for Array and Date.
287 */
288 public Iterable<Symbol> getAllSymbolsForTypeOf(Symbol sym) {
289 return getAllSymbolsForType(sym.getType());
290 }
291
292 /**
293 * Returns the global scope.
294 */
295 public SymbolScope getGlobalScope() {
296 return globalScope;
297 }
298
299 /**
300 * Gets the symbol for the given constructor or interface.
301 */
302 public Symbol getSymbolDeclaredBy(FunctionType fn) {
303 Preconditions.checkState(fn.isConstructor() || fn.isInterface());
304 ObjectType instanceType = fn.getInstanceType();
305 return getSymbolForName(fn.getSource(), instanceType.getReferenceName());
306 }
307
308 /**
309 * Gets the symbol for the given enum.
310 */
311 public Symbol getSymbolDeclaredBy(EnumType enumType) {
312 return getSymbolForName(null,
313 enumType.getElementsType().getReferenceName());
314 }
315
316 /**
317 * Gets the symbol for the prototype if this is the symbol for a constructor
318 * or interface.
319 */
320 public Symbol getSymbolForInstancesOf(Symbol sym) {
321 FunctionType fn = sym.getFunctionType();
322 if (fn != null && fn.isNominalConstructor()) {
323 return getSymbolForInstancesOf(fn);
324 }
325 return null;
326 }
327
328 /**
329 * Gets the symbol for the prototype of the given constructor or interface.
330 */
331 public Symbol getSymbolForInstancesOf(FunctionType fn) {
332 Preconditions.checkState(fn.isConstructor() || fn.isInterface());
333 ObjectType pType = fn.getPrototype();
334 return getSymbolForName(fn.getSource(), pType.getReferenceName());
335 }
336
337 private Symbol getSymbolForName(Node source, String name) {
338 if (name == null || globalScope == null) {
339 return null;
340 }
341
342 SymbolScope scope = source == null ?
343 globalScope : getEnclosingScope(source);
344
345 // scope will sometimes be null if one of the type-stripping passes
346 // was run, and the symbol isn't in the AST anymore.
347 return scope == null ? null : scope.getQualifiedSlot(name);
348 }
349
350 /**
351 * Gets all symbols associated with the given type.
352 * For union types, this may be multiple symbols.
353 * For instance types, this will return the constructor of
354 * that instance.
355 */
356 public List<Symbol> getAllSymbolsForType(JSType type) {
357 if (type == null) {
358 return ImmutableList.of();
359 }
360
361 UnionType unionType = type.toMaybeUnionType();
362 if (unionType != null) {
363 List<Symbol> result = Lists.newArrayListWithExpectedSize(2);
364 for (JSType alt : unionType.getAlternates()) {
365 // Our type system never has nested unions.
366 Symbol altSym = getSymbolForTypeHelper(alt, true);
367 if (altSym != null) {
368 result.add(altSym);
369 }
370 }
371 return result;
372 }
373 Symbol result = getSymbolForTypeHelper(type, true);
374 return result == null
375 ? ImmutableList.<Symbol>of() : ImmutableList.of(result);
376 }
377
378 /**
379 * Gets all symbols associated with the given type.
380 * If there is more that one symbol associated with the given type,
381 * return null.
382 * @param type The type.
383 * @param linkToCtor If true, we should link instance types back
384 * to their constructor function. If false, we should link
385 * instance types back to their prototype. See the comments
386 * at the top of this file for more information on how
387 * our internal type system is more granular than Symbols.
388 */
389 private Symbol getSymbolForTypeHelper(JSType type, boolean linkToCtor) {
390 if (type == null) {
391 return null;
392 }
393
394 if (type.isGlobalThisType()) {
395 return globalScope.getSlot(GLOBAL_THIS);
396 } else if (type.isNominalConstructor()) {
397 return linkToCtor ?
398 globalScope.getSlot("Function") :
399 getSymbolDeclaredBy(type.toMaybeFunctionType());
400 } else if (type.isFunctionPrototypeType()) {
401 FunctionType ownerFn = ((ObjectType) type).getOwnerFunction();
402 if (!ownerFn.isConstructor() && !ownerFn.isInterface()) {
403 return null;
404 }
405 return linkToCtor ?
406 getSymbolDeclaredBy(ownerFn) :
407 getSymbolForInstancesOf(ownerFn);
408 } else if (type.isInstanceType()) {
409 FunctionType ownerFn = ((ObjectType) type).getConstructor();
410 return linkToCtor ?
411 getSymbolDeclaredBy(ownerFn) :
412 getSymbolForInstancesOf(ownerFn);
413 } else if (type.isFunctionType()) {
414 return linkToCtor ?
415 globalScope.getSlot("Function") :
416 globalScope.getQualifiedSlot("Function.prototype");
417 } else if (type.autoboxesTo() != null) {
418 return getSymbolForTypeHelper(type.autoboxesTo(), linkToCtor);
419 } else {
420 return null;
421 }
422 }
423
424 public String toDebugString() {
425 StringBuilder builder = new StringBuilder();
426 for (Symbol symbol : getAllSymbols()) {
427 toDebugString(builder, symbol);
428 }
429 return builder.toString();
430 }
431
432 private void toDebugString(StringBuilder builder, Symbol symbol) {
433 SymbolScope scope = symbol.scope;
434 if (scope.isGlobalScope()) {
435 builder.append(
436 String.format("'%s' : in global scope:\n", symbol.getName()));
437 } else if (scope.getRootNode() != null) {
438 builder.append(
439 String.format("'%s' : in scope %s:%d\n",
440 symbol.getName(),
441 scope.getRootNode().getSourceFileName(),
442 scope.getRootNode().getLineno()));
443 } else if (scope.getSymbolForScope() != null) {
444 builder.append(
445 String.format("'%s' : in scope %s\n", symbol.getName(),
446 scope.getSymbolForScope().getName()));
447 } else {
448 builder.append(
449 String.format("'%s' : in unknown scope\n", symbol.getName()));
450 }
451
452 int refCount = 0;
453 for (Reference ref : getReferences(symbol)) {
454 builder.append(
455 String.format(" Ref %d: %s:%d\n",
456 refCount,
457 ref.getNode().getSourceFileName(),
458 ref.getNode().getLineno()));
459 refCount++;
460 }
461 }
462
463 /**
464 * Make sure all the given scopes in {@code otherSymbolTable}
465 * are in this symbol table.
466 */
467 <S extends StaticScope<JSType>>
468 void addScopes(Collection<S> scopes) {
469 for (S scope : scopes) {
470 createScopeFrom(scope);
471 }
472 }
473
474 /** Finds all the scopes and adds them to this symbol table. */
475 void findScopes(AbstractCompiler compiler, Node externs, Node root) {
476 NodeTraversal.traverseRoots(
477 compiler,
478 Lists.newArrayList(externs, root),
479 new NodeTraversal.AbstractScopedCallback() {
480 @Override
481 public void enterScope(NodeTraversal t) {
482 createScopeFrom(t.getScope());
483 }
484
485 @Override
486 public void visit(NodeTraversal t, Node n, Node p) {}
487 });
488 }
489
490 /** Gets all the scopes in this symbol table. */
491 public Collection<SymbolScope> getAllScopes() {
492 return Collections.unmodifiableCollection(scopes.values());
493 }
494
495 /**
496 * Finds anonymous functions in local scopes, and gives them names
497 * and symbols. They will show up as local variables with names
498 * "function%0", "function%1", etc.
499 */
500 public void addAnonymousFunctions() {
501 TreeSet<SymbolScope> scopes = Sets.newTreeSet(LEXICAL_SCOPE_ORDERING);
502 for (SymbolScope scope : getAllScopes()) {
503 if (scope.isLexicalScope()) {
504 scopes.add(scope);
505 }
506 }
507
508 for (SymbolScope scope : scopes) {
509 addAnonymousFunctionsInScope(scope);
510 }
511 }
512
513 private void addAnonymousFunctionsInScope(SymbolScope scope) {
514 Symbol sym = getSymbolForScope(scope);
515 if (sym == null) {
516 // JSCompiler has no symbol for this scope. Check to see if it's a
517 // local function. If it is, give it a name.
518 if (scope.isLexicalScope() &&
519 !scope.isGlobalScope() &&
520 scope.getRootNode() != null &&
521 !scope.getRootNode().isFromExterns() &&
522 scope.getParentScope() != null) {
523 SymbolScope parent = scope.getParentScope();
524
525 int count = parent.innerAnonFunctionsWithNames++;
526 String innerName = "function%" + count;
527 scope.setSymbolForScope(
528 declareInferredSymbol(
529 parent, innerName, scope.getRootNode()));
530 }
531 }
532 }
533
534 /**
535 * Make sure all the symbols and references in {@code otherSymbolTable}
536 * are in this symbol table.
537 *
538 * Uniqueness of symbols and references is determined by the associated
539 * node.
540 *
541 * If multiple symbol tables are mixed in, we do not check for consistency
542 * between symbol tables. The first symbol we see dictates the type
543 * information for that symbol.
544 */
545 <S extends StaticSlot<JSType>, R extends StaticReference<JSType>>
546 void addSymbolsFrom(StaticSymbolTable<S, R> otherSymbolTable) {
547 for (S otherSymbol : otherSymbolTable.getAllSymbols()) {
548 String name = otherSymbol.getName();
549 SymbolScope myScope = createScopeFrom(
550 otherSymbolTable.getScope(otherSymbol));
551
552 StaticReference<JSType> decl =
553 findBestDeclToAdd(otherSymbolTable, otherSymbol);
554 Symbol mySymbol = null;
555 if (decl != null) {
556 Node declNode = decl.getNode();
557
558 // If we have a declaration node, we can ensure the symbol is declared.
559 mySymbol = isAnySymbolDeclared(name, declNode, myScope);
560 if (mySymbol == null) {
561 mySymbol = copySymbolTo(otherSymbol, declNode, myScope);
562 }
563 } else {
564 // If we don't have a declaration node, we won't be able to declare
565 // a symbol in this symbol table. But we may be able to salvage the
566 // references if we already have a symbol.
567 mySymbol = myScope.getOwnSlot(name);
568 }
569
570 if (mySymbol != null) {
571 for (R otherRef : otherSymbolTable.getReferences(otherSymbol)) {
572 if (isGoodRefToAdd(otherRef)) {
573 mySymbol.defineReferenceAt(otherRef.getNode());
574 }
575 }
576 }
577 }
578 }
579
580 /**
581 * Checks if any symbol is already declared at the given node and scope
582 * for the given name. If so, returns it.
583 */
584 private Symbol isAnySymbolDeclared(
585 String name, Node declNode, SymbolScope scope) {
586 Symbol sym = symbols.get(declNode, name);
587 if (sym == null) {
588 // Sometimes, our symbol tables will disagree on where the
589 // declaration node should be. In the rare case where this happens,
590 // trust the existing symbol.
591 // See SymbolTableTest#testDeclarationDisagreement.
592 return scope.ownSymbols.get(name);
593 }
594 return sym;
595 }
596
597 /** Helper for addSymbolsFrom, to determine the best declaration spot. */
598 private <S extends StaticSlot<JSType>, R extends StaticReference<JSType>>
599 StaticReference<JSType> findBestDeclToAdd(
600 StaticSymbolTable<S, R> otherSymbolTable, S slot) {
601 StaticReference<JSType> decl = slot.getDeclaration();
602 if (isGoodRefToAdd(decl)) {
603 return decl;
604 }
605
606 for (R ref : otherSymbolTable.getReferences(slot)) {
607 if (isGoodRefToAdd(ref)) {
608 return ref;
609 }
610 }
611
612 return null;
613 }
614
615 /**
616 * Helper for addSymbolsFrom, to determine whether a reference is
617 * acceptable. A reference must be in the normal source tree.
618 */
619 private boolean isGoodRefToAdd(@Nullable StaticReference<JSType> ref) {
620 return ref != null && ref.getNode() != null
621 && ref.getNode().getStaticSourceFile() != null
622 && !Compiler.SYNTHETIC_EXTERNS.equals(
623 ref.getNode().getStaticSourceFile().getName());
624 }
625
626 private Symbol copySymbolTo(StaticSlot<JSType> sym, SymbolScope scope) {
627 return copySymbolTo(sym, sym.getDeclaration().getNode(), scope);
628 }
629
630 private Symbol copySymbolTo(
631 StaticSlot<JSType> sym, Node declNode, SymbolScope scope) {
632 // All symbols must have declaration nodes.
633 Preconditions.checkNotNull(declNode);
634 return declareSymbol(
635 sym.getName(), sym.getType(), sym.isTypeInferred(), scope, declNode,
636 sym.getJSDocInfo());
637 }
638
639 private Symbol addSymbol(
640 String name, JSType type, boolean inferred, SymbolScope scope,
641 Node declNode) {
642 Symbol symbol = new Symbol(name, type, inferred, scope);
643 Symbol replacedSymbol = symbols.put(declNode, name, symbol);
644 Preconditions.checkState(
645 replacedSymbol == null,
646 "Found duplicate symbol %s in global index. Type %s", name, type);
647
648 replacedSymbol = scope.ownSymbols.put(name, symbol);
649 Preconditions.checkState(
650 replacedSymbol == null,
651 "Found duplicate symbol %s in its scope. Type %s", name, type);
652 return symbol;
653 }
654
655 private Symbol declareSymbol(
656 String name, JSType type, boolean inferred,
657 SymbolScope scope, Node declNode, JSDocInfo info) {
658 Symbol symbol = addSymbol(name, type, inferred, scope, declNode);
659 symbol.setJSDocInfo(info);
660 symbol.setDeclaration(symbol.defineReferenceAt(declNode));
661 return symbol;
662 }
663
664 private void removeSymbol(Symbol s) {
665 SymbolScope scope = getScope(s);
666 if (scope.ownSymbols.remove(s.getName()) != s) {
667 throw new IllegalStateException("Symbol not found in scope " + s);
668 }
669 if (symbols.remove(s.getDeclaration().getNode(), s.getName()) != s) {
670 throw new IllegalStateException("Symbol not found in table " + s);
671 }
672 }
673
674 /**
675 * Not all symbol tables record references to "namespace" objects.
676 * For example, if you have:
677 * goog.dom.DomHelper = function() {};
678 * The symbol table may not record that as a reference to "goog.dom",
679 * because that would be redundant.
680 */
681 void fillNamespaceReferences() {
682 for (Symbol symbol : getAllSymbolsSorted()) {
683 String qName = symbol.getName();
684 int rootIndex = qName.indexOf('.');
685 if (rootIndex == -1) {
686 continue;
687 }
688
689 Symbol root = symbol.scope.getQualifiedSlot(
690 qName.substring(0, rootIndex));
691 if (root == null) {
692 // In theory, this should never happen, but we fail quietly anyway
693 // just to be safe.
694 continue;
695 }
696
697 for (Reference ref : getReferences(symbol)) {
698 Node currentNode = ref.getNode();
699 if (!currentNode.isQualifiedName()) {
700 continue;
701 }
702
703 while (currentNode.isGetProp()) {
704 currentNode = currentNode.getFirstChild();
705
706 String name = currentNode.getQualifiedName();
707 if (name != null) {
708 Symbol namespace =
709 isAnySymbolDeclared(name, currentNode, root.scope);
710 if (namespace == null) {
711 namespace = root.scope.getQualifiedSlot(name);
712 }
713
714 if (namespace == null && root.scope.isGlobalScope()) {
715 namespace = declareSymbol(name,
716 registry.getNativeType(JSTypeNative.UNKNOWN_TYPE),
717 true,
718 root.scope,
719 currentNode,
720 null /* JsDoc info */);
721 }
722
723 if (namespace != null) {
724 namespace.defineReferenceAt(currentNode);
725 }
726 }
727 }
728 }
729 }
730 }
731
732 void fillPropertyScopes() {
733 // Collect all object symbols.
734 List<Symbol> types = Lists.newArrayList();
735
736 // Create a property scope for each named type and each anonymous object,
737 // and populate it with that object's properties.
738 //
739 // We notably don't want to create a property scope for 'x' in
740 // var x = new Foo();
741 // where x is just an instance of another type.
742 for (Symbol sym : getAllSymbols()) {
743 if (needsPropertyScope(sym)) {
744 types.add(sym);
745 }
746 }
747
748 // The order of operations here is significant.
749 //
750 // When we add properties to Foo, we'll remove Foo.prototype from
751 // the symbol table and replace it with a fresh symbol in Foo's
752 // property scope. So the symbol for Foo.prototype in
753 // {@code instances} will be stale.
754 //
755 // To prevent this, we sort the list by the reverse of the
756 // default symbol order, which will do the right thing.
757 Collections.sort(types,
758 Collections.reverseOrder(getNaturalSymbolOrdering()));
759 for (Symbol s : types) {
760 createPropertyScopeFor(s);
761 }
762
763 pruneOrphanedNames();
764 }
765
766 private boolean needsPropertyScope(Symbol sym) {
767 ObjectType type = ObjectType.cast(sym.getType());
768 if (type == null) {
769 return false;
770 }
771
772 // Anonymous objects
773 if (type.getReferenceName() == null) {
774 return true;
775 }
776
777 // Constructors/prototypes
778 // Should this check for
779 // (type.isNominalConstructor() || type.isFunctionPrototypeType())
780 // ?
781 if (sym.getName().equals(type.getReferenceName())) {
782 return true;
783 }
784
785 // Enums
786 if (type.isEnumType() &&
787 sym.getName().equals(
788 type.toMaybeEnumType().getElementsType().getReferenceName())) {
789 return true;
790 }
791
792 return false;
793 }
794
795 /**
796 * Removes symbols where the namespace they're on has been removed.
797 *
798 * After filling property scopes, we may have two symbols represented
799 * in different ways. For example, "A.superClass_.foo" and B.prototype.foo".
800 *
801 * This resolves that ambiguity by pruning the duplicates.
802 * If we have a lexical symbol with a constructor in its property
803 * chain, then we assume there's also a property path to this symbol.
804 * In other words, we can remove "A.superClass_.foo" because it's rooted
805 * at "A", and we built a property scope for "A" above.
806 */
807 void pruneOrphanedNames() {
808 nextSymbol: for (Symbol s : getAllSymbolsSorted()) {
809 if (s.isProperty()) {
810 continue;
811 }
812
813 String currentName = s.getName();
814 int dot = -1;
815 while (-1 != (dot = currentName.lastIndexOf('.'))) {
816 currentName = currentName.substring(0, dot);
817
818 Symbol owner = s.scope.getQualifiedSlot(currentName);
819 if (owner != null
820 && owner.getType() != null
821 && (owner.getType().isNominalConstructor() ||
822 owner.getType().isFunctionPrototypeType() ||
823 owner.getType().isEnumType())) {
824 removeSymbol(s);
825 continue nextSymbol;
826 }
827 }
828 }
829 }
830
831 /**
832 * Create symbols and references for all properties of types in
833 * this symbol table.
834 *
835 * This gets a little bit tricky, because of the way this symbol table
836 * conflates "type Foo" and "the constructor of type Foo". So if you
837 * have:
838 *
839 * <code>
840 * SymbolTable symbolTable = for("var x = new Foo();");
841 * Symbol x = symbolTable.getGlobalScope().getSlot("x");
842 * Symbol type = symbolTable.getAllSymbolsForType(x.getType()).get(0);
843 * </code>
844 *
845 * Then type.getPropertyScope() will have the properties of the
846 * constructor "Foo". To get the properties of instances of "Foo",
847 * you will need to call:
848 *
849 * <code>
850 * Symbol instance = symbolTable.getSymbolForInstancesOf(type);
851 * </code>
852 *
853 * As described at the top of this file, notice that "new Foo()" and
854 * "Foo.prototype" are represented by the same symbol.
855 */
856 void fillPropertySymbols(
857 AbstractCompiler compiler, Node externs, Node root) {
858 (new PropertyRefCollector(compiler)).process(externs, root);
859 }
860
861 /** Index JSDocInfo. */
862 void fillJSDocInfo(
863 AbstractCompiler compiler, Node externs, Node root) {
864 NodeTraversal.traverseRoots(
865 compiler, Lists.newArrayList(externs, root),
866 new JSDocInfoCollector(compiler.getTypeRegistry()));
867
868 // Create references to parameters in the JSDoc.
869 for (Symbol sym : getAllSymbolsSorted()) {
870 JSDocInfo info = sym.getJSDocInfo();
871 if (info == null) {
872 continue;
873 }
874
875 for (Marker marker : info.getMarkers()) {
876 SourcePosition<Node> pos = marker.getNameNode();
877 if (pos == null) {
878 continue;
879 }
880
881 Node paramNode = pos.getItem();
882 String name = paramNode.getString();
883 Symbol param = getParameterInFunction(sym, name);
884 if (param == null) {
885 // There is no reference to this parameter in the actual JavaScript
886 // code, so we'll try to create a special JsDoc-only symbol in
887 // a JsDoc-only scope.
888 SourcePosition<Node> typePos = marker.getType();
889 JSType type = null;
890 if (typePos != null) {
891 type = typePos.getItem().getJSType();
892 }
893
894 if (sym.docScope == null) {
895 sym.docScope = new SymbolScope(null /* root */,
896 null /* parent scope */, null /* type of this */, sym);
897 }
898
899 // Check to make sure there's no existing symbol. In theory, this
900 // should never happen, but we check anyway and fail silently
901 // if our assumptions are wrong. (We do not want to put the symbol
902 // table into an invalid state).
903 Symbol existingSymbol =
904 isAnySymbolDeclared(name, paramNode, sym.docScope);
905 if (existingSymbol == null) {
906 declareSymbol(name, type, type == null, sym.docScope, paramNode,
907 null /* info */);
908 }
909 } else {
910 param.defineReferenceAt(paramNode);
911 }
912 }
913 }
914 }
915
916 /**
917 * Build a property scope for the given symbol. Any properties of the symbol
918 * will be added to the property scope.
919 *
920 * It is important that property scopes are created in order from the leaves
921 * up to the root, so this should only be called from #fillPropertyScopes.
922 * If you try to create a property scope for a parent before its leaf,
923 * then the leaf will get cut and re-added to the parent property scope,
924 * and weird things will happen.
925 */
926 private void createPropertyScopeFor(Symbol s) {
927 // In order to build a property scope for s, we will need to build
928 // a property scope for all its implicit prototypes first. This means
929 // that sometimes we will already have built its property scope
930 // for a previous symbol.
931 if (s.propertyScope != null) {
932 return;
933 }
934
935 SymbolScope parentPropertyScope = null;
936 ObjectType type = s.getType() == null ? null : s.getType().toObjectType();
937 if (type == null) {
938 return;
939 }
940
941 ObjectType proto = type.getParentScope();
942 if (proto != null && proto != type && proto.getConstructor() != null) {
943 Symbol parentSymbol = getSymbolForInstancesOf(proto.getConstructor());
944 if (parentSymbol != null) {
945 createPropertyScopeFor(parentSymbol);
946 parentPropertyScope = parentSymbol.getPropertyScope();
947 }
948 }
949
950 ObjectType instanceType = type;
951 Iterable<String> propNames = type.getOwnPropertyNames();
952 if (instanceType.isFunctionPrototypeType()) {
953 // Guard against modifying foo.prototype when foo is a regular (non-constructor) function.
954 if (instanceType.getOwnerFunction().hasInstanceType()) {
955 // Merge the properties of "Foo.prototype" and "new Foo()" together.
956 instanceType = instanceType.getOwnerFunction().getInstanceType();
957 Set<String> set = Sets.newHashSet(propNames);
958 Iterables.addAll(set, instanceType.getOwnPropertyNames());
959 propNames = set;
960 }
961 }
962
963 s.setPropertyScope(new SymbolScope(null, parentPropertyScope, type, s));
964 for (String propName : propNames) {
965 StaticSlot<JSType> newProp = instanceType.getSlot(propName);
966 if (newProp.getDeclaration() == null) {
967 // Skip properties without declarations. We won't know how to index
968 // them, because we index things by node.
969 continue;
970 }
971
972 // We have symbol tables that do not do type analysis. They just try
973 // to build a complete index of all objects in the program. So we might
974 // already have symbols for things like "Foo.bar". If this happens,
975 // throw out the old symbol and use the type-based symbol.
976 Symbol oldProp = symbols.get(newProp.getDeclaration().getNode(),
977 s.getName() + "." + propName);
978 if (oldProp != null) {
979 removeSymbol(oldProp);
980 }
981
982 // If we've already have an entry in the table for this symbol,
983 // then skip it. This should only happen if we screwed up,
984 // and declared multiple distinct properties with the same name
985 // at the same node. We bail out here to be safe.
986 if (symbols.get(newProp.getDeclaration().getNode(),
987 newProp.getName()) != null) {
988 logger.warning("Found duplicate symbol " + newProp);
989 continue;
990 }
991
992 Symbol newSym = copySymbolTo(newProp, s.propertyScope);
993 if (oldProp != null) {
994 if (newSym.getJSDocInfo() == null) {
995 newSym.setJSDocInfo(oldProp.getJSDocInfo());
996 }
997 newSym.setPropertyScope(oldProp.propertyScope);
998 for (Reference ref : oldProp.references.values()) {
999 newSym.defineReferenceAt(ref.getNode());
1000 }
1001 }
1002 }
1003 }
1004
1005 /**
1006 * Fill in references to "this" variables.
1007 */
1008 void fillThisReferences(
1009 AbstractCompiler compiler, Node externs, Node root) {
1010 (new ThisRefCollector(compiler)).process(externs, root);
1011 }
1012
1013 /**
1014 * Given a scope from another symbol table, returns the {@code SymbolScope}
1015 * rooted at the same node. Creates one if it doesn't exist yet.
1016 */
1017 private SymbolScope createScopeFrom(StaticScope<JSType> otherScope) {
1018 Node otherScopeRoot = otherScope.getRootNode();
1019 SymbolScope myScope = scopes.get(otherScopeRoot);
1020 if (myScope == null) {
1021 StaticScope<JSType> otherScopeParent = otherScope.getParentScope();
1022
1023 // If otherScope is a global scope, and we already have a global scope,
1024 // then something has gone seriously wrong.
1025 //
1026 // Not all symbol tables are rooted at the same global node, and
1027 // we do not want to mix and match symbol tables that are rooted
1028 // differently.
1029
1030 if (otherScopeParent == null) {
1031 // The global scope must be created before any local scopes.
1032 Preconditions.checkState(
1033 globalScope == null, "Global scopes found at different roots");
1034 }
1035
1036 myScope = new SymbolScope(
1037 otherScopeRoot,
1038 otherScopeParent == null ? null : createScopeFrom(otherScopeParent),
1039 otherScope.getTypeOfThis(),
1040 null);
1041 scopes.put(otherScopeRoot, myScope);
1042 if (myScope.isGlobalScope()) {
1043 globalScope = myScope;
1044 }
1045 }
1046 return myScope;
1047 }
1048
1049 public static final class Symbol extends SimpleSlot {
1050 // Use a linked hash map, so that the results are deterministic
1051 // (and so the declaration always comes first).
1052 private final Map<Node, Reference> references = Maps.newLinkedHashMap();
1053
1054 private final SymbolScope scope;
1055
1056 private SymbolScope propertyScope = null;
1057
1058 private Reference declaration = null;
1059
1060 private JSDocInfo docInfo = null;
1061
1062 // A scope for symbols that are only documented in JSDoc.
1063 private SymbolScope docScope = null;
1064
1065 Symbol(String name, JSType type, boolean inferred, SymbolScope scope) {
1066 super(name, type, inferred);
1067 this.scope = scope;
1068 }
1069
1070 @Override
1071 public Reference getDeclaration() {
1072 return declaration;
1073 }
1074
1075 public FunctionType getFunctionType() {
1076 return JSType.toMaybeFunctionType(getType());
1077 }
1078
1079 public Reference defineReferenceAt(Node n) {
1080 Reference result = references.get(n);
1081 if (result == null) {
1082 result = new Reference(this, n);
1083 references.put(n, result);
1084 }
1085 return result;
1086 }
1087
1088 /** Sets the declaration node. May only be called once. */
1089 void setDeclaration(Reference ref) {
1090 Preconditions.checkState(this.declaration == null);
1091 this.declaration = ref;
1092 }
1093
1094 public boolean inGlobalScope() {
1095 return scope.isGlobalScope();
1096 }
1097
1098 public boolean inExterns() {
1099 Node n = getDeclarationNode();
1100 return n == null ? false : n.isFromExterns();
1101 }
1102
1103 public Node getDeclarationNode() {
1104 return declaration == null ? null : declaration.getNode();
1105 }
1106
1107 public String getSourceFileName() {
1108 Node n = getDeclarationNode();
1109 return n == null ? null : n.getSourceFileName();
1110 }
1111
1112 public SymbolScope getPropertyScope() {
1113 return propertyScope;
1114 }
1115
1116 void setPropertyScope(SymbolScope scope) {
1117 this.propertyScope = scope;
1118 if (scope != null) {
1119 this.propertyScope.setSymbolForScope(this);
1120 }
1121 }
1122
1123 @Override
1124 public JSDocInfo getJSDocInfo() {
1125 return docInfo;
1126 }
1127
1128 void setJSDocInfo(JSDocInfo info) {
1129 this.docInfo = info;
1130 }
1131
1132 /** Whether this is a property of another variable. */
1133 public boolean isProperty() {
1134 return scope.isPropertyScope();
1135 }
1136
1137 /** Whether this is a variable in a lexical scope. */
1138 public boolean isLexicalVariable() {
1139 return scope.isLexicalScope();
1140 }
1141
1142 /** Whether this is a variable that's only in JSDoc. */
1143 public boolean isDocOnlyParameter() {
1144 return scope.isDocScope();
1145 }
1146
1147 @Override
1148 public String toString() {
1149 Node n = getDeclarationNode();
1150 int lineNo = n == null ? -1 : n.getLineno();
1151 return getName() + "@" + getSourceFileName() + ":" + lineNo;
1152 }
1153 }
1154
1155 public static final class Reference extends SimpleReference<Symbol> {
1156 Reference(Symbol symbol, Node node) {
1157 super(symbol, node);
1158 }
1159 }
1160
1161 public static final class SymbolScope implements StaticScope<JSType> {
1162 private final Node rootNode;
1163 private final SymbolScope parent;
1164 private final JSType typeOfThis;
1165 private final Map<String, Symbol> ownSymbols = Maps.newLinkedHashMap();
1166 private final int scopeDepth;
1167
1168 // The number of inner anonymous functions that we've given names to.
1169 private int innerAnonFunctionsWithNames = 0;
1170
1171 // The symbol associated with a property scope or doc scope.
1172 private Symbol mySymbol;
1173
1174 SymbolScope(
1175 Node rootNode,
1176 @Nullable SymbolScope parent,
1177 JSType typeOfThis,
1178 Symbol mySymbol) {
1179 this.rootNode = rootNode;
1180 this.parent = parent;
1181 this.typeOfThis = typeOfThis;
1182 this.scopeDepth = parent == null ? 0 : (parent.getScopeDepth() + 1);
1183 this.mySymbol = mySymbol;
1184 }
1185
1186 Symbol getSymbolForScope() {
1187 return mySymbol;
1188 }
1189
1190 void setSymbolForScope(Symbol sym) {
1191 this.mySymbol = sym;
1192 }
1193
1194 /** Gets a unique index for the symbol in this scope. */
1195 public int getIndexOfSymbol(Symbol sym) {
1196 return Iterables.indexOf(
1197 ownSymbols.values(), Predicates.equalTo(sym));
1198 }
1199
1200 @Override
1201 public Node getRootNode() {
1202 return rootNode;
1203 }
1204
1205 @Override
1206 public SymbolScope getParentScope() {
1207 return parent;
1208 }
1209
1210 /**
1211 * Get the slot for a fully-qualified name (e.g., "a.b.c") by trying
1212 * to find property scopes at each part of the path.
1213 */
1214 public Symbol getQualifiedSlot(String name) {
1215 Symbol fullyNamedSym = getSlot(name);
1216 if (fullyNamedSym != null) {
1217 return fullyNamedSym;
1218 }
1219
1220 int dot = name.lastIndexOf(".");
1221 if (dot != -1) {
1222 Symbol owner = getQualifiedSlot(name.substring(0, dot));
1223 if (owner != null && owner.getPropertyScope() != null) {
1224 return owner.getPropertyScope().getSlot(name.substring(dot + 1));
1225 }
1226 }
1227
1228 return null;
1229 }
1230
1231 @Override
1232 public Symbol getSlot(String name) {
1233 Symbol own = getOwnSlot(name);
1234 if (own != null) {
1235 return own;
1236 }
1237
1238 Symbol ancestor = parent == null ? null : parent.getSlot(name);
1239 if (ancestor != null) {
1240 return ancestor;
1241 }
1242 return null;
1243 }
1244
1245 @Override
1246 public Symbol getOwnSlot(String name) {
1247 return ownSymbols.get(name);
1248 }
1249
1250 @Override
1251 public JSType getTypeOfThis() {
1252 return typeOfThis;
1253 }
1254
1255 public boolean isGlobalScope() {
1256 return getParentScope() == null && getRootNode() != null;
1257 }
1258
1259 /**
1260 * Returns whether this is a doc scope. A doc scope is a table for symbols
1261 * that are documented solely within a JSDoc comment.
1262 */
1263 public boolean isDocScope() {
1264 return getRootNode() == null && mySymbol != null &&
1265 mySymbol.docScope == this;
1266 }
1267
1268 public boolean isPropertyScope() {
1269 return getRootNode() == null && !isDocScope();
1270 }
1271
1272 public boolean isLexicalScope() {
1273 return getRootNode() != null;
1274 }
1275
1276 public int getScopeDepth() {
1277 return scopeDepth;
1278 }
1279
1280 @Override
1281 public String toString() {
1282 Node n = getRootNode();
1283 if (n != null) {
1284 return "Scope@" + n.getSourceFileName() + ":" + n.getLineno();
1285 } else {
1286 return "PropertyScope@" + getSymbolForScope();
1287 }
1288 }
1289 }
1290
1291 private class PropertyRefCollector
1292 extends NodeTraversal.AbstractPostOrderCallback
1293 implements CompilerPass {
1294 private final AbstractCompiler compiler;
1295
1296 PropertyRefCollector(AbstractCompiler compiler) {
1297 this.compiler = compiler;
1298 }
1299
1300 @Override
1301 public void process(Node externs, Node root) {
1302 NodeTraversal.traverseRoots(
1303 compiler,
1304 Lists.newArrayList(externs, root),
1305 this);
1306 }
1307
1308 private boolean maybeDefineReference(
1309 Node n, String propName, Symbol ownerSymbol) {
1310 // getPropertyScope() will be null in some rare cases where there
1311 // are no extern declarations for built-in types (like Function).
1312 if (ownerSymbol != null && ownerSymbol.getPropertyScope() != null) {
1313 Symbol prop = ownerSymbol.getPropertyScope().getSlot(propName);
1314 if (prop != null) {
1315 prop.defineReferenceAt(n);
1316 return true;
1317 }
1318 }
1319 return false;
1320 }
1321
1322 // Try to find the symbol by its fully qualified name.
1323 private boolean tryDefineLexicalQualifiedNameRef(String name, Node n) {
1324 if (name != null) {
1325 Symbol lexicalSym = getEnclosingScope(n).getQualifiedSlot(name);
1326 if (lexicalSym != null) {
1327 lexicalSym.defineReferenceAt(n);
1328 return true;
1329 }
1330 }
1331 return false;
1332 }
1333
1334 // Try to remove a reference by its fully qualified name.
1335 // If the symbol has no references left, remove it completely.
1336 private void tryRemoveLexicalQualifiedNameRef(String name, Node n) {
1337 if (name != null) {
1338 Symbol lexicalSym = getEnclosingScope(n).getQualifiedSlot(name);
1339 if (lexicalSym != null &&
1340 lexicalSym.isLexicalVariable() &&
1341 lexicalSym.getDeclaration().getNode() == n) {
1342 removeSymbol(lexicalSym);
1343 }
1344 }
1345 }
1346
1347 private boolean maybeDefineTypedReference(
1348 Node n, String propName, JSType owner) {
1349 if (owner.isGlobalThisType()) {
1350 Symbol sym = globalScope.getSlot(propName);
1351 if (sym != null) {
1352 sym.defineReferenceAt(n);
1353 return true;
1354 }
1355 } else if (owner.isNominalConstructor()) {
1356 return maybeDefineReference(
1357 n, propName, getSymbolDeclaredBy(owner.toMaybeFunctionType()));
1358 } else if (owner.isEnumType()) {
1359 return maybeDefineReference(
1360 n, propName, getSymbolDeclaredBy(owner.toMaybeEnumType()));
1361 } else {
1362 boolean defined = false;
1363 for (Symbol ctor : getAllSymbolsForType(owner)) {
1364 if (maybeDefineReference(
1365 n, propName, getSymbolForInstancesOf(ctor))) {
1366 defined = true;
1367 }
1368 }
1369 return defined;
1370 }
1371 return false;
1372 }
1373
1374 @Override
1375 public void visit(NodeTraversal t, Node n, Node parent) {
1376 // There are two ways to define a property reference:
1377 // 1) As a fully qualified lexical symbol (e.g., x.y)
1378 // 2) As a property of another object (e.g., x's y)
1379 // Property definitions should take precedence over lexical
1380 // definitions. e.g., for "a.b", it's more useful to record
1381 // this as "property b of the type of a", than as "symbol a.b".
1382
1383 if (n.isGetProp()) {
1384 JSType owner = n.getFirstChild().getJSType();
1385 if (owner != null) {
1386 boolean defined = maybeDefineTypedReference(
1387 n, n.getLastChild().getString(), owner);
1388
1389 if (defined) {
1390 tryRemoveLexicalQualifiedNameRef(n.getQualifiedName(), n);
1391 return;
1392 }
1393 }
1394
1395 tryDefineLexicalQualifiedNameRef(n.getQualifiedName(), n);
1396 } else if (n.isStringKey()) {
1397 JSType owner = parent.getJSType();
1398 if (owner != null) {
1399 boolean defined =
1400 maybeDefineTypedReference(n, n.getString(), owner);
1401
1402 if (defined) {
1403 tryRemoveLexicalQualifiedNameRef(
1404 NodeUtil.getBestLValueName(n), n);
1405 return;
1406 }
1407 }
1408
1409 tryDefineLexicalQualifiedNameRef(
1410 NodeUtil.getBestLValueName(n), n);
1411 }
1412 }
1413 }
1414
1415 private class ThisRefCollector
1416 extends NodeTraversal.AbstractScopedCallback
1417 implements CompilerPass {
1418 private final AbstractCompiler compiler;
1419
1420 // The 'this' symbols in the current scope chain.
1421 //
1422 // If we don't know how to declare 'this' in a scope chain,
1423 // then null should be on the stack. But this should be a rare
1424 // occurrence. We should strive to always be able to come up
1425 // with some symbol for 'this'.
1426 private final List<Symbol> thisStack = Lists.newArrayList();
1427
1428 ThisRefCollector(AbstractCompiler compiler) {
1429 this.compiler = compiler;
1430 }
1431
1432 @Override
1433 public void process(Node externs, Node root) {
1434 NodeTraversal.traverseRoots(
1435 compiler,
1436 Lists.newArrayList(externs, root),
1437 this);
1438 }
1439
1440 @Override
1441 public void enterScope(NodeTraversal t) {
1442 Symbol symbol = null;
1443 if (t.inGlobalScope()) {
1444 // Declare the global this at the first input root.
1445 // This is a bizarre place to put it, but we need some
1446 // location with a real file path (because all symbols
1447 // must have a path).
1448 // Note that root.lastChild.firstChild is the first non-extern input.
1449 Node firstInputRoot = t.getScopeRoot().getLastChild().getFirstChild();
1450 if (firstInputRoot != null) {
1451 symbol = addSymbol(
1452 GLOBAL_THIS,
1453 registry.getNativeType(JSTypeNative.GLOBAL_THIS),
1454 false /* declared */,
1455 globalScope,
1456 firstInputRoot);
1457 symbol.setDeclaration(new Reference(symbol, firstInputRoot));
1458 }
1459 } else {
1460 // Otherwise, declare a "this" property when possible.
1461 SymbolScope scope = scopes.get(t.getScopeRoot());
1462 Preconditions.checkNotNull(scope);
1463 Symbol scopeSymbol = getSymbolForScope(scope);
1464 if (scopeSymbol != null) {
1465 SymbolScope propScope = scopeSymbol.getPropertyScope();
1466 if (propScope != null) {
1467 // If a function is assigned multiple times, we only want
1468 // one addressable "this" symbol.
1469 symbol = propScope.getOwnSlot("this");
1470 if (symbol == null) {
1471 JSType rootType = t.getScopeRoot().getJSType();
1472 FunctionType fnType = rootType == null
1473 ? null : rootType.toMaybeFunctionType();
1474 JSType type = fnType == null
1475 ? null : fnType.getTypeOfThis();
1476 symbol = addSymbol(
1477 "this",
1478 type,
1479 false /* declared */,
1480 scope,
1481 t.getScopeRoot());
1482 }
1483
1484 // TODO(nicksantos): It's non-obvious where the declaration of
1485 // the 'this' symbol should be. Figure this out later.
1486 }
1487 }
1488 }
1489
1490 thisStack.add(symbol);
1491 }
1492
1493 @Override
1494 public void exitScope(NodeTraversal t) {
1495 thisStack.remove(thisStack.size() - 1);
1496 }
1497
1498 @Override
1499 public void visit(NodeTraversal t, Node n, Node parent) {
1500 if (!n.isThis()) {
1501 return;
1502 }
1503
1504 Symbol symbol = thisStack.get(thisStack.size() - 1);
1505 if (symbol != null) {
1506 Reference ref = symbol.defineReferenceAt(n);
1507 if (symbol.getDeclaration() == null) {
1508 symbol.setDeclaration(ref);
1509 }
1510 }
1511 }
1512 }
1513
1514 /** Collects references to types in JSDocInfo. */
1515 private class JSDocInfoCollector
1516 extends NodeTraversal.AbstractPostOrderCallback {
1517 private final JSTypeRegistry typeRegistry;
1518
1519 private JSDocInfoCollector(JSTypeRegistry registry) {
1520 this.typeRegistry = registry;
1521 }
1522
1523 @Override public void visit(NodeTraversal t, Node n, Node parent) {
1524 if (n.getJSDocInfo() != null) {
1525
1526 // Find references in the JSDocInfo.
1527 JSDocInfo info = n.getJSDocInfo();
1528 docInfos.add(info);
1529
1530 for (Node typeAst : info.getTypeNodes()) {
1531 SymbolScope scope = scopes.get(t.getScopeRoot());
1532 visitTypeNode(scope == null ? globalScope : scope, typeAst);
1533 }
1534 }
1535 }
1536
1537 public void visitTypeNode(SymbolScope scope, Node n) {
1538 if (n.isString()) {
1539 Symbol symbol = scope.getSlot(n.getString());
1540 if (symbol == null) {
1541 // If we can't find this type, it might be a reference to a
1542 // primitive type (like {string}). Autobox it to check.
1543 JSType type = typeRegistry.getType(n.getString());
1544 JSType autobox = type == null ? null : type.autoboxesTo();
1545 symbol = autobox == null
1546 ? null : getSymbolForTypeHelper(autobox, true);
1547 }
1548 if (symbol != null) {
1549 symbol.defineReferenceAt(n);
1550 }
1551 }
1552
1553 for (Node child = n.getFirstChild();
1554 child != null; child = child.getNext()) {
1555 visitTypeNode(scope, child);
1556 }
1557 }
1558 }
1559
1560 // Comparators
1561 private final Ordering<String> SOURCE_NAME_ORDERING =
1562 Ordering.natural().nullsFirst();
1563
1564 private final Ordering<Node> NODE_ORDERING = new Ordering<Node>() {
1565 @Override
1566 public int compare(Node a, Node b) {
1567 int result = SOURCE_NAME_ORDERING.compare(
1568 a.getSourceFileName(), b.getSourceFileName());
1569 if (result != 0) {
1570 return result;
1571 }
1572
1573 // Source position is a bit mask of line in the top 4 bits, so this
1574 // is a quick way to compare order without computing absolute position.
1575 return a.getSourcePosition() - b.getSourcePosition();
1576 }
1577 };
1578
1579 private final Ordering<SymbolScope> LEXICAL_SCOPE_ORDERING =
1580 new Ordering<SymbolScope>() {
1581 @Override
1582 public int compare(SymbolScope a, SymbolScope b) {
1583 Preconditions.checkState(a.isLexicalScope() && b.isLexicalScope(),
1584 "We can only sort lexical scopes");
1585 return NODE_ORDERING.compare(a.getRootNode(), b.getRootNode());
1586 }
1587 };
1588
1589 private final Ordering<Symbol> SYMBOL_ORDERING = new Ordering<Symbol>() {
1590 @Override
1591 public int compare(Symbol a, Symbol b) {
1592 SymbolScope scopeA = getScope(a);
1593 SymbolScope scopeB = getScope(b);
1594
1595 // More deeply nested symbols should go later.
1596 int result = getLexicalScopeDepth(scopeA) - getLexicalScopeDepth(scopeB);
1597 if (result != 0) {
1598 return result;
1599 }
1600
1601 // After than, just use lexicographic ordering.
1602 // This ensures "a.b" comes before "a.b.c".
1603 return a.getName().compareTo(b.getName());
1604 }
1605 };
1606
1607 /**
1608 * For a lexical scope, just returns the normal scope depth.
1609 *
1610 * For a property scope, returns the number of scopes we have to search
1611 * to find the nearest lexical scope, plus that lexical scope's depth.
1612 *
1613 * For a doc info scope, returns 0.
1614 */
1615 private int getLexicalScopeDepth(SymbolScope scope) {
1616 if (scope.isLexicalScope() || scope.isDocScope()) {
1617 return scope.getScopeDepth();
1618 } else {
1619 Preconditions.checkState(scope.isPropertyScope());
1620 Symbol sym = scope.getSymbolForScope();
1621 Preconditions.checkNotNull(sym);
1622 return getLexicalScopeDepth(getScope(sym)) + 1;
1623 }
1624 }
1625 }