Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2004 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.Predicate;
21 import com.google.common.collect.ImmutableList;
22 import com.google.common.collect.Iterators;
23 import com.google.javascript.rhino.ErrorReporter;
24 import com.google.javascript.rhino.JSDocInfo;
25 import com.google.javascript.rhino.Node;
26 import com.google.javascript.rhino.jstype.JSType;
27 import com.google.javascript.rhino.jstype.ObjectType;
28 import com.google.javascript.rhino.jstype.StaticReference;
29 import com.google.javascript.rhino.jstype.StaticScope;
30 import com.google.javascript.rhino.jstype.StaticSlot;
31 import com.google.javascript.rhino.jstype.StaticSourceFile;
32 import com.google.javascript.rhino.jstype.StaticSymbolTable;
33
34 import java.util.Collections;
35 import java.util.Iterator;
36 import java.util.LinkedHashMap;
37 import java.util.Map;
38
39 /**
40 * Scope contains information about a variable scope in JavaScript.
41 * Scopes can be nested, a scope points back to its parent scope.
42 * A Scope contains information about variables defined in that scope.
43 * <p>
44 * A Scope is also used as a lattice element for flow-sensitive type inference.
45 * As a lattice element, a Scope is viewed as a map from names to types. A name
46 * not in the map is considered to have the bottom type. The join of two maps m1
47 * and m2 is the map of the union of names with {@link JSType#getLeastSupertype}
48 * to meet the m1 type and m2 type.
49 *
50 * @see NodeTraversal
51 * @see DataFlowAnalysis
52 *
53 */
54 public class Scope
55 implements StaticScope<JSType>, StaticSymbolTable<Scope.Var, Scope.Var> {
56 private final Map<String, Var> vars = new LinkedHashMap<String, Var>();
57 private final Scope parent;
58 private final int depth;
59 private final Node rootNode;
60
61 /** Whether this is a bottom scope for the purposes of type inference. */
62 private final boolean isBottom;
63
64 private Var arguments;
65
66 private static final Predicate<Var> DECLARATIVELY_UNBOUND_VARS_WITHOUT_TYPES =
67 new Predicate<Var>() {
68 @Override public boolean apply(Var var) {
69 return var.getParentNode() != null &&
70 var.getType() == null && // no declared type
71 var.getParentNode().isVar() &&
72 !var.isExtern();
73 }
74 };
75
76 /** Stores info about a variable */
77 public static class Var
78 implements StaticSlot<JSType>, StaticReference<JSType> {
79 /** name */
80 final String name;
81
82 /** Var node */
83 final Node nameNode;
84
85 /**
86 * The variable's type.
87 */
88 private JSType type;
89
90 /**
91 * Whether the variable's type has been inferred or is declared. An inferred
92 * type may change over time (as more code is discovered), whereas a
93 * declared type is a static contract that must be matched.
94 */
95 private final boolean typeInferred;
96
97 /** Input source */
98 final CompilerInput input;
99
100 /**
101 * The index at which the var is declared. e..g if it's 0, it's the first
102 * declared variable in that scope
103 */
104 final int index;
105
106 /** The enclosing scope */
107 final Scope scope;
108
109 /** @see #isMarkedEscaped */
110 private boolean markedEscaped = false;
111
112 /** @see #isMarkedAssignedExactlyOnce */
113 private boolean markedAssignedExactlyOnce = false;
114
115 /**
116 * Creates a variable.
117 *
118 * @param inferred whether its type is inferred (as opposed to declared)
119 */
120 private Var(boolean inferred, String name, Node nameNode, JSType type,
121 Scope scope, int index, CompilerInput input) {
122 this.name = name;
123 this.nameNode = nameNode;
124 this.type = type;
125 this.scope = scope;
126 this.index = index;
127 this.input = input;
128 this.typeInferred = inferred;
129 }
130
131 /**
132 * Gets the name of the variable.
133 */
134 @Override
135 public String getName() {
136 return name;
137 }
138
139 /**
140 * Gets the node for the name of the variable.
141 */
142 @Override
143 public Node getNode() {
144 return nameNode;
145 }
146
147 CompilerInput getInput() {
148 return input;
149 }
150
151 @Override
152 public StaticSourceFile getSourceFile() {
153 return nameNode.getStaticSourceFile();
154 }
155
156 @Override
157 public Var getSymbol() {
158 return this;
159 }
160
161 @Override
162 public Var getDeclaration() {
163 return nameNode == null ? null : this;
164 }
165
166 /**
167 * Gets the parent of the name node.
168 */
169 public Node getParentNode() {
170 return nameNode == null ? null : nameNode.getParent();
171 }
172
173 /**
174 * Whether this is a bleeding function (an anonymous named function
175 * that bleeds into the inner scope).
176 */
177 public boolean isBleedingFunction() {
178 return NodeUtil.isFunctionExpression(getParentNode());
179 }
180
181 /**
182 * Gets the scope where this variable is declared.
183 */
184 Scope getScope() {
185 return scope;
186 }
187
188 /**
189 * Returns whether this is a global variable.
190 */
191 public boolean isGlobal() {
192 return scope.isGlobal();
193 }
194
195 /**
196 * Returns whether this is a local variable.
197 */
198 public boolean isLocal() {
199 return scope.isLocal();
200 }
201
202 /**
203 * Returns whether this is defined in an extern file.
204 */
205 boolean isExtern() {
206 return input == null || input.isExtern();
207 }
208
209 /**
210 * Returns {@code true} if the variable is declared as a constant,
211 * based on the value reported by {@code NodeUtil}.
212 */
213 public boolean isConst() {
214 return nameNode != null && NodeUtil.isConstantName(nameNode);
215 }
216
217 /**
218 * Returns {@code true} if the variable is declared as a define.
219 * A variable is a define if it is annotated by {@code @define}.
220 */
221 public boolean isDefine() {
222 JSDocInfo info = getJSDocInfo();
223 return info != null && info.isDefine();
224 }
225
226 public Node getInitialValue() {
227 return NodeUtil.getRValueOfLValue(nameNode);
228 }
229
230 /**
231 * Gets this variable's type. To know whether this type has been inferred,
232 * see {@code #isTypeInferred()}.
233 */
234 @Override
235 public JSType getType() {
236 return type;
237 }
238
239 /**
240 * Returns the name node that produced this variable.
241 */
242 public Node getNameNode() {
243 return nameNode;
244 }
245
246 /**
247 * Gets the JSDocInfo for the variable.
248 */
249 @Override
250 public JSDocInfo getJSDocInfo() {
251 return nameNode == null ? null : NodeUtil.getBestJSDocInfo(nameNode);
252 }
253
254 /**
255 * Sets this variable's type.
256 * @throws IllegalStateException if the variable's type is not inferred
257 */
258 void setType(JSType type) {
259 Preconditions.checkState(isTypeInferred());
260 this.type = type;
261 }
262
263 /**
264 * Resolve this variable's type.
265 */
266 void resolveType(ErrorReporter errorReporter) {
267 if (type != null) {
268 type = type.resolve(errorReporter, scope);
269 }
270 }
271
272 /**
273 * Returns whether this variable's type is inferred. To get the variable's
274 * type, see {@link #getType()}.
275 */
276 @Override
277 public boolean isTypeInferred() {
278 return typeInferred;
279 }
280
281 public String getInputName() {
282 if (input == null)
283 return "<non-file>";
284 else
285 return input.getName();
286 }
287
288 public boolean isNoShadow() {
289 JSDocInfo info = getJSDocInfo();
290 return info != null && info.isNoShadow();
291 }
292
293 @Override public boolean equals(Object other) {
294 if (!(other instanceof Var)) {
295 return false;
296 }
297
298 Var otherVar = (Var) other;
299 return otherVar.nameNode == nameNode;
300 }
301
302 @Override public int hashCode() {
303 return nameNode.hashCode();
304 }
305
306 @Override
307 public String toString() {
308 return "Scope.Var " + name + "{" + type + "}";
309 }
310
311 /**
312 * Record that this is escaped by an inner scope.
313 *
314 * In other words, it's assigned in an inner scope so that it's much harder
315 * to make assertions about its value at a given point.
316 */
317 void markEscaped() {
318 markedEscaped = true;
319 }
320
321 /**
322 * Whether this is escaped by an inner scope.
323 * Notice that not all scope creators record this information.
324 */
325 boolean isMarkedEscaped() {
326 return markedEscaped;
327 }
328
329 /**
330 * Record that this is assigned exactly once..
331 *
332 * In other words, it's assigned in an inner scope so that it's much harder
333 * to make assertions about its value at a given point.
334 */
335 void markAssignedExactlyOnce() {
336 markedAssignedExactlyOnce = true;
337 }
338
339 /**
340 * Whether this is assigned exactly once.
341 * Notice that not all scope creators record this information.
342 */
343 boolean isMarkedAssignedExactlyOnce() {
344 return markedAssignedExactlyOnce;
345 }
346 }
347
348 /**
349 * A special subclass of Var used to distinguish "arguments" in the current
350 * scope.
351 */
352 // TODO(johnlenz): Include this the list of Vars for the scope.
353 public static class Arguments extends Var {
354 Arguments(Scope scope) {
355 super(
356 false, // no inferred
357 "arguments", // always arguments
358 null, // no declaration node
359 // TODO(johnlenz): provide the type of "Arguments".
360 null, // no type info
361 scope,
362 -1, // no variable index
363 null // input
364 );
365 }
366
367 @Override public boolean equals(Object other) {
368 if (!(other instanceof Arguments)) {
369 return false;
370 }
371
372 Arguments otherVar = (Arguments) other;
373 return otherVar.scope.getRootNode() == scope.getRootNode();
374 }
375
376 @Override public int hashCode() {
377 return System.identityHashCode(this);
378 }
379 }
380
381 /**
382 * Creates a Scope given the parent Scope and the root node of the scope.
383 * @param parent The parent Scope. Cannot be null.
384 * @param rootNode Typically the FUNCTION node.
385 */
386 Scope(Scope parent, Node rootNode) {
387 Preconditions.checkNotNull(parent);
388 Preconditions.checkArgument(rootNode != parent.rootNode);
389
390 this.parent = parent;
391 this.rootNode = rootNode;
392 this.isBottom = false;
393 this.depth = parent.depth + 1;
394 }
395
396 /**
397 * Creates a empty Scope (bottom of the lattice).
398 * @param rootNode Typically a FUNCTION node or the global BLOCK node.
399 * @param isBottom Whether this is the bottom of a lattice. Otherwise,
400 * it must be a global scope.
401 */
402 private Scope(Node rootNode, boolean isBottom) {
403 this.parent = null;
404 this.rootNode = rootNode;
405 this.isBottom = isBottom;
406 this.depth = 0;
407 }
408
409 static Scope createGlobalScope(Node rootNode) {
410 return new Scope(rootNode, false);
411 }
412
413 static Scope createLatticeBottom(Node rootNode) {
414 return new Scope(rootNode, true);
415 }
416
417 /** The depth of the scope. The global scope has depth 0. */
418 int getDepth() {
419 return depth;
420 }
421
422 /** Whether this is the bottom of the lattice. */
423 boolean isBottom() {
424 return isBottom;
425 }
426
427 /**
428 * Gets the container node of the scope. This is typically the FUNCTION
429 * node or the global BLOCK/SCRIPT node.
430 */
431 @Override
432 public Node getRootNode() {
433 return rootNode;
434 }
435
436 public Scope getParent() {
437 return parent;
438 }
439
440 Scope getGlobalScope() {
441 Scope result = this;
442 while (result.getParent() != null) {
443 result = result.getParent();
444 }
445 return result;
446 }
447
448 @Override
449 public StaticScope<JSType> getParentScope() {
450 return parent;
451 }
452
453 /**
454 * Gets the type of {@code this} in the current scope.
455 */
456 @Override
457 public JSType getTypeOfThis() {
458 if (isGlobal()) {
459 return ObjectType.cast(rootNode.getJSType());
460 }
461
462 Preconditions.checkState(rootNode.isFunction());
463 JSType nodeType = rootNode.getJSType();
464 if (nodeType != null && nodeType.isFunctionType()) {
465 return nodeType.toMaybeFunctionType().getTypeOfThis();
466 } else {
467 return parent.getTypeOfThis();
468 }
469 }
470
471 /**
472 * Declares a variable whose type is inferred.
473 *
474 * @param name name of the variable
475 * @param nameNode the NAME node declaring the variable
476 * @param type the variable's type
477 * @param input the input in which this variable is defined.
478 */
479 Var declare(String name, Node nameNode, JSType type, CompilerInput input) {
480 return declare(name, nameNode, type, input, true);
481 }
482
483 /**
484 * Declares a variable.
485 *
486 * @param name name of the variable
487 * @param nameNode the NAME node declaring the variable
488 * @param type the variable's type
489 * @param input the input in which this variable is defined.
490 * @param inferred Whether this variable's type is inferred (as opposed
491 * to declared).
492 */
493 Var declare(String name, Node nameNode,
494 JSType type, CompilerInput input, boolean inferred) {
495 Preconditions.checkState(name != null && name.length() > 0);
496
497 // Make sure that it's declared only once
498 Preconditions.checkState(vars.get(name) == null);
499
500 Var var = new Var(inferred, name, nameNode, type, this, vars.size(), input);
501 vars.put(name, var);
502 return var;
503 }
504
505 /**
506 * Undeclares a variable, to be used when the compiler optimizes out
507 * a variable and removes it from the scope.
508 */
509 void undeclare(Var var) {
510 Preconditions.checkState(var.scope == this);
511 Preconditions.checkState(vars.get(var.name) == var);
512 vars.remove(var.name);
513 }
514
515 @Override
516 public Var getSlot(String name) {
517 return getVar(name);
518 }
519
520 @Override
521 public Var getOwnSlot(String name) {
522 return vars.get(name);
523 }
524
525 /**
526 * Returns the variable, may be null
527 */
528 public Var getVar(String name) {
529 Var var = vars.get(name);
530 if (var != null) {
531 return var;
532 } else if (parent != null) { // Recurse up the parent Scope
533 return parent.getVar(name);
534 } else {
535 return null;
536 }
537 }
538
539 /**
540 * Get a unique VAR object to represents "arguments" within this scope
541 */
542 public Var getArgumentsVar() {
543 if (arguments == null) {
544 arguments = new Arguments(this);
545 }
546 return arguments;
547 }
548
549 /**
550 * Returns true if a variable is declared.
551 */
552 public boolean isDeclared(String name, boolean recurse) {
553 Scope scope = this;
554 if (scope.vars.containsKey(name))
555 return true;
556
557 if (scope.parent != null && recurse) {
558 return scope.parent.isDeclared(name, recurse);
559 }
560 return false;
561 }
562
563 /**
564 * Return an iterator over all of the variables declared in this scope.
565 */
566 public Iterator<Var> getVars() {
567 return vars.values().iterator();
568 }
569
570 /**
571 * Return an iterable over all of the variables declared in this scope.
572 */
573 Iterable<Var> getVarIterable() {
574 return vars.values();
575 }
576
577 @Override
578 public Iterable<Var> getReferences(Var var) {
579 return ImmutableList.of(var);
580 }
581
582 @Override
583 public StaticScope<JSType> getScope(Var var) {
584 return var.scope;
585 }
586
587 @Override
588 public Iterable<Var> getAllSymbols() {
589 return Collections.unmodifiableCollection(vars.values());
590 }
591
592 /**
593 * Returns number of variables in this scope
594 */
595 public int getVarCount() {
596 return vars.size();
597 }
598
599 /**
600 * Returns whether this is the global scope.
601 */
602 public boolean isGlobal() {
603 return parent == null;
604 }
605
606 /**
607 * Returns whether this is a local scope (i.e. not the global scope).
608 */
609 public boolean isLocal() {
610 return !isGlobal();
611 }
612
613 /**
614 * Gets all variables declared with "var" but without declared types attached.
615 */
616 public Iterator<Var> getDeclarativelyUnboundVarsWithoutTypes() {
617 return Iterators.filter(
618 getVars(), DECLARATIVELY_UNBOUND_VARS_WITHOUT_TYPES);
619 }
620 }