Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2008 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.annotations.VisibleForTesting;
20 import com.google.common.base.Preconditions;
21 import com.google.common.base.Predicate;
22 import com.google.common.base.Predicates;
23 import com.google.common.collect.ImmutableSet;
24 import com.google.common.collect.Lists;
25 import com.google.common.collect.Maps;
26 import com.google.javascript.jscomp.NodeTraversal.ScopedCallback;
27 import com.google.javascript.jscomp.Scope.Var;
28 import com.google.javascript.rhino.InputId;
29 import com.google.javascript.rhino.Node;
30 import com.google.javascript.rhino.Token;
31 import com.google.javascript.rhino.jstype.JSType;
32 import com.google.javascript.rhino.jstype.StaticReference;
33 import com.google.javascript.rhino.jstype.StaticSourceFile;
34 import com.google.javascript.rhino.jstype.StaticSymbolTable;
35
36 import java.util.ArrayDeque;
37 import java.util.Deque;
38 import java.util.Iterator;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.Set;
42
43 /**
44 * A helper class for passes that want to access all information about where a
45 * variable is referenced and declared at once and then make a decision as to
46 * how it should be handled, possibly inlining, reordering, or generating
47 * warnings. Callers do this by providing {@link Behavior} and then
48 * calling {@link #process(Node, Node)}.
49 *
50 * @author [email protected] (Kushal Dave)
51 */
52 class ReferenceCollectingCallback implements ScopedCallback,
53 HotSwapCompilerPass,
54 StaticSymbolTable<Var, ReferenceCollectingCallback.Reference> {
55
56 /**
57 * Maps a given variable to a collection of references to that name. Note that
58 * Var objects are not stable across multiple traversals (unlike scope root or
59 * name).
60 */
61 private final Map<Var, ReferenceCollection> referenceMap =
62 Maps.newHashMap();
63
64 /**
65 * The stack of basic blocks and scopes the current traversal is in.
66 */
67 private final Deque<BasicBlock> blockStack = new ArrayDeque<BasicBlock>();
68
69 /**
70 * Source of behavior at various points in the traversal.
71 */
72 private final Behavior behavior;
73
74 /**
75 * JavaScript compiler to use in traversing.
76 */
77 private final AbstractCompiler compiler;
78
79 /**
80 * Only collect references for filtered variables.
81 */
82 private final Predicate<Var> varFilter;
83
84 /**
85 * Constructor initializes block stack.
86 */
87 ReferenceCollectingCallback(AbstractCompiler compiler, Behavior behavior) {
88 this(compiler, behavior, Predicates.<Var>alwaysTrue());
89 }
90
91 /**
92 * Constructor only collects references that match the given variable.
93 *
94 * The test for Var equality uses reference equality, so it's necessary to
95 * inject a scope when you traverse.
96 */
97 ReferenceCollectingCallback(AbstractCompiler compiler, Behavior behavior,
98 Predicate<Var> varFilter) {
99 this.compiler = compiler;
100 this.behavior = behavior;
101 this.varFilter = varFilter;
102 }
103
104 /**
105 * Convenience method for running this pass over a tree with this
106 * class as a callback.
107 */
108 @Override
109 public void process(Node externs, Node root) {
110 NodeTraversal.traverseRoots(
111 compiler, Lists.newArrayList(externs, root), this);
112 }
113
114 /**
115 * Same as process but only runs on a part of AST associated to one script.
116 */
117 @Override
118 public void hotSwapScript(Node scriptRoot, Node originalRoot) {
119 NodeTraversal.traverse(compiler, scriptRoot, this);
120 }
121
122 /**
123 * Gets the variables that were referenced in this callback.
124 */
125 @Override
126 public Iterable<Var> getAllSymbols() {
127 return referenceMap.keySet();
128 }
129
130 @Override
131 public Scope getScope(Var var) {
132 return var.scope;
133 }
134
135 /**
136 * Gets the reference collection for the given variable.
137 */
138 @Override
139 public ReferenceCollection getReferences(Var v) {
140 return referenceMap.get(v);
141 }
142
143 /**
144 * For each node, update the block stack and reference collection
145 * as appropriate.
146 */
147 @Override
148 public void visit(NodeTraversal t, Node n, Node parent) {
149 if (n.isName()) {
150 Var v;
151 if (n.getString().equals("arguments")) {
152 v = t.getScope().getArgumentsVar();
153 } else {
154 v = t.getScope().getVar(n.getString());
155 }
156 if (v != null && varFilter.apply(v)) {
157 addReference(v, new Reference(n, t, blockStack.peek()));
158 }
159 }
160
161 if (isBlockBoundary(n, parent)) {
162 blockStack.pop();
163 }
164 }
165
166 /**
167 * Updates block stack and invokes any additional behavior.
168 */
169 @Override
170 public void enterScope(NodeTraversal t) {
171 Node n = t.getScope().getRootNode();
172 BasicBlock parent = blockStack.isEmpty() ? null : blockStack.peek();
173 blockStack.push(new BasicBlock(parent, n));
174 }
175
176 /**
177 * Updates block stack and invokes any additional behavior.
178 */
179 @Override
180 public void exitScope(NodeTraversal t) {
181 blockStack.pop();
182 if (t.getScope().isGlobal()) {
183 // Update global scope reference lists when we are done with it.
184 compiler.updateGlobalVarReferences(referenceMap, t.getScopeRoot());
185 behavior.afterExitScope(t, compiler.getGlobalVarReferences());
186 } else {
187 behavior.afterExitScope(t, new ReferenceMapWrapper(referenceMap));
188 }
189 }
190
191 /**
192 * Updates block stack.
193 */
194 @Override
195 public boolean shouldTraverse(NodeTraversal nodeTraversal, Node n,
196 Node parent) {
197 // If node is a new basic block, put on basic block stack
198 if (isBlockBoundary(n, parent)) {
199 blockStack.push(new BasicBlock(blockStack.peek(), n));
200 }
201 return true;
202 }
203
204 /**
205 * @return true if this node marks the start of a new basic block
206 */
207 private static boolean isBlockBoundary(Node n, Node parent) {
208 if (parent != null) {
209 switch (parent.getType()) {
210 case Token.DO:
211 case Token.FOR:
212 case Token.TRY:
213 case Token.WHILE:
214 case Token.WITH:
215 // NOTE: TRY has up to 3 child blocks:
216 // TRY
217 // BLOCK
218 // BLOCK
219 // CATCH
220 // BLOCK
221 // Note that there is an explicit CATCH token but no explicit
222 // FINALLY token. For simplicity, we consider each BLOCK
223 // a separate basic BLOCK.
224 return true;
225 case Token.AND:
226 case Token.HOOK:
227 case Token.IF:
228 case Token.OR:
229 // The first child of a conditional is not a boundary,
230 // but all the rest of the children are.
231 return n != parent.getFirstChild();
232
233 }
234 }
235
236 return n.isCase();
237 }
238
239 private void addReference(Var v, Reference reference) {
240 // Create collection if none already
241 ReferenceCollection referenceInfo = referenceMap.get(v);
242 if (referenceInfo == null) {
243 referenceInfo = new ReferenceCollection();
244 referenceMap.put(v, referenceInfo);
245 }
246
247 // Add this particular reference
248 referenceInfo.add(reference);
249 }
250
251 interface ReferenceMap {
252 ReferenceCollection getReferences(Var var);
253 }
254
255 private static class ReferenceMapWrapper implements ReferenceMap {
256 private final Map<Var, ReferenceCollection> referenceMap;
257
258 public ReferenceMapWrapper(Map<Var, ReferenceCollection> referenceMap) {
259 this.referenceMap = referenceMap;
260 }
261
262 @Override
263 public ReferenceCollection getReferences(Var var) {
264 return referenceMap.get(var);
265 }
266 }
267
268 /**
269 * Way for callers to add specific behavior during traversal that
270 * utilizes the built-up reference information.
271 */
272 interface Behavior {
273 /**
274 * Called after we finish with a scope.
275 */
276 void afterExitScope(NodeTraversal t, ReferenceMap referenceMap);
277 }
278
279 static Behavior DO_NOTHING_BEHAVIOR = new Behavior() {
280 @Override
281 public void afterExitScope(NodeTraversal t, ReferenceMap referenceMap) {}
282 };
283
284 /**
285 * A collection of references. Can be subclassed to apply checks or
286 * store additional state when adding.
287 */
288 static class ReferenceCollection implements Iterable<Reference> {
289
290 List<Reference> references = Lists.newArrayList();
291
292 @Override
293 public Iterator<Reference> iterator() {
294 return references.iterator();
295 }
296
297 void add(Reference reference) {
298 references.add(reference);
299 }
300
301 /**
302 * Determines if the variable for this reference collection is
303 * "well-defined." A variable is well-defined if we can prove at
304 * compile-time that it's assigned a value before it's used.
305 *
306 * Notice that if this function returns false, this doesn't imply that the
307 * variable is used before it's assigned. It just means that we don't
308 * have enough information to make a definitive judgment.
309 */
310 protected boolean isWellDefined() {
311 int size = references.size();
312 if (size == 0) {
313 return false;
314 }
315
316 // If this is a declaration that does not instantiate the variable,
317 // it's not well-defined.
318 Reference init = getInitializingReference();
319 if (init == null) {
320 return false;
321 }
322
323 Preconditions.checkState(references.get(0).isDeclaration());
324 BasicBlock initBlock = init.getBasicBlock();
325 for (int i = 1; i < size; i++) {
326 if (!initBlock.provablyExecutesBefore(
327 references.get(i).getBasicBlock())) {
328 return false;
329 }
330 }
331
332 return true;
333 }
334
335 /**
336 * Whether the variable is escaped into an inner scope.
337 */
338 boolean isEscaped() {
339 Scope scope = null;
340 for (Reference ref : references) {
341 if (scope == null) {
342 scope = ref.scope;
343 } else if (scope != ref.scope) {
344 return true;
345 }
346 }
347 return false;
348 }
349
350 /**
351 * @param index The index into the references array to look for an
352 * assigning declaration.
353 *
354 * This is either the declaration if a value is assigned (such as
355 * "var a = 2", "function a()...", "... catch (a)...").
356 */
357 private boolean isInitializingDeclarationAt(int index) {
358 Reference maybeInit = references.get(index);
359 if (maybeInit.isInitializingDeclaration()) {
360 // This is a declaration that represents the initial value.
361 // Specifically, var declarations without assignments such as "var a;"
362 // are not.
363 return true;
364 }
365 return false;
366 }
367
368 /**
369 * @param index The index into the references array to look for an
370 * initialized assignment reference. That is, an assignment immediately
371 * follow a variable declaration that itself does not initialize the
372 * variable.
373 */
374 private boolean isInitializingAssignmentAt(int index) {
375 if (index < references.size() && index > 0) {
376 Reference maybeDecl = references.get(index-1);
377 if (maybeDecl.isVarDeclaration()) {
378 Preconditions.checkState(!maybeDecl.isInitializingDeclaration());
379 Reference maybeInit = references.get(index);
380 if (maybeInit.isSimpleAssignmentToName()) {
381 return true;
382 }
383 }
384 }
385 return false;
386 }
387
388 /**
389 * @return The reference that provides the value for the variable at the
390 * time of the first read, if known, otherwise null.
391 *
392 * This is either the variable declaration ("var a = ...") or first
393 * reference following the declaration if it is an assignment.
394 */
395 Reference getInitializingReference() {
396 if (isInitializingDeclarationAt(0)) {
397 return references.get(0);
398 } else if (isInitializingAssignmentAt(1)) {
399 return references.get(1);
400 }
401 return null;
402 }
403
404 /**
405 * Constants are allowed to be defined after their first use.
406 */
407 Reference getInitializingReferenceForConstants() {
408 int size = references.size();
409 for (int i = 0; i < size; i++) {
410 if (isInitializingDeclarationAt(i) || isInitializingAssignmentAt(i)) {
411 return references.get(i);
412 }
413 }
414 return null;
415 }
416
417 /**
418 * @return Whether the variable is only assigned a value once for its
419 * lifetime.
420 */
421 boolean isAssignedOnceInLifetime() {
422 Reference ref = getOneAndOnlyAssignment();
423 if (ref == null) {
424 return false;
425 }
426
427 // Make sure this assignment is not in a loop.
428 for (BasicBlock block = ref.getBasicBlock();
429 block != null; block = block.getParent()) {
430 if (block.isFunction) {
431 break;
432 } else if (block.isLoop) {
433 return false;
434 }
435 }
436
437 return true;
438 }
439
440 /**
441 * @return The one and only assignment. Returns if there are 0 or 2+
442 * assignments.
443 */
444 private Reference getOneAndOnlyAssignment() {
445 Reference assignment = null;
446 int size = references.size();
447 for (int i = 0; i < size; i++) {
448 Reference ref = references.get(i);
449 if (ref.isLvalue() || ref.isInitializingDeclaration()) {
450 if (assignment == null) {
451 assignment = ref;
452 } else {
453 return null;
454 }
455 }
456 }
457 return assignment;
458 }
459
460 /**
461 * @return Whether the variable is never assigned a value.
462 */
463 boolean isNeverAssigned() {
464 int size = references.size();
465 for (int i = 0; i < size; i++) {
466 Reference ref = references.get(i);
467 if (ref.isLvalue() || ref.isInitializingDeclaration()) {
468 return false;
469 }
470 }
471 return true;
472 }
473
474 boolean firstReferenceIsAssigningDeclaration() {
475 int size = references.size();
476 if (size > 0 && references.get(0).isInitializingDeclaration()) {
477 return true;
478 }
479 return false;
480 }
481 }
482
483 /**
484 * Represents a single declaration or reference to a variable.
485 */
486 static final class Reference implements StaticReference<JSType> {
487
488 private static final Set<Integer> DECLARATION_PARENTS =
489 ImmutableSet.of(Token.VAR, Token.FUNCTION, Token.CATCH);
490
491 private final Node nameNode;
492 private final BasicBlock basicBlock;
493 private final Scope scope;
494 private final InputId inputId;
495 private final StaticSourceFile sourceFile;
496
497 Reference(Node nameNode, NodeTraversal t,
498 BasicBlock basicBlock) {
499 this(nameNode, basicBlock, t.getScope(), t.getInput().getInputId());
500 }
501
502 // Bleeding functions are weird, because the declaration does
503 // not appear inside their scope. So they need their own constructor.
504 static Reference newBleedingFunction(NodeTraversal t,
505 BasicBlock basicBlock, Node func) {
506 return new Reference(func.getFirstChild(),
507 basicBlock, t.getScope(), t.getInput().getInputId());
508 }
509
510 /**
511 * Creates a variable reference in a given script file name, used in tests.
512 *
513 * @return The created reference.
514 */
515 @VisibleForTesting
516 static Reference createRefForTest(CompilerInput input) {
517 return new Reference(new Node(Token.NAME), null, null,
518 input.getInputId());
519 }
520
521 private Reference(Node nameNode,
522 BasicBlock basicBlock, Scope scope, InputId inputId) {
523 this.nameNode = nameNode;
524 this.basicBlock = basicBlock;
525 this.scope = scope;
526 this.inputId = inputId;
527 this.sourceFile = nameNode.getStaticSourceFile();
528 }
529
530 /**
531 * Makes a copy of the current reference using a new Scope instance.
532 */
533 Reference cloneWithNewScope(Scope newScope) {
534 return new Reference(nameNode, basicBlock, newScope, inputId);
535 }
536
537 @Override
538 public Var getSymbol() {
539 return scope.getVar(nameNode.getString());
540 }
541
542 @Override
543 public Node getNode() {
544 return nameNode;
545 }
546
547 public InputId getInputId() {
548 return inputId;
549 }
550
551 @Override
552 public StaticSourceFile getSourceFile() {
553 return sourceFile;
554 }
555
556 boolean isDeclaration() {
557 Node parent = getParent();
558 Node grandparent = parent.getParent();
559 return DECLARATION_PARENTS.contains(parent.getType()) ||
560 parent.isParamList() &&
561 grandparent.isFunction();
562 }
563
564 boolean isVarDeclaration() {
565 return getParent().isVar();
566 }
567
568 boolean isHoistedFunction() {
569 return NodeUtil.isHoistedFunctionDeclaration(getParent());
570 }
571
572 /**
573 * Determines whether the variable is initialized at the declaration.
574 */
575 boolean isInitializingDeclaration() {
576 // VAR is the only type of variable declaration that may not initialize
577 // its variable. Catch blocks, named functions, and parameters all do.
578 return isDeclaration() &&
579 !getParent().isVar() ||
580 nameNode.getFirstChild() != null;
581 }
582
583 /**
584 * @return For an assignment, variable declaration, or function declaration
585 * return the assigned value, otherwise null.
586 */
587 Node getAssignedValue() {
588 Node parent = getParent();
589 return (parent.isFunction())
590 ? parent : NodeUtil.getAssignedValue(nameNode);
591 }
592
593 BasicBlock getBasicBlock() {
594 return basicBlock;
595 }
596
597 Node getParent() {
598 return getNode().getParent();
599 }
600
601 Node getGrandparent() {
602 Node parent = getParent();
603 return parent == null ? null : parent.getParent();
604 }
605
606 private static boolean isLhsOfForInExpression(Node n) {
607 Node parent = n.getParent();
608 if (parent.isVar()) {
609 return isLhsOfForInExpression(parent);
610 }
611 return NodeUtil.isForIn(parent) && parent.getFirstChild() == n;
612 }
613
614 boolean isSimpleAssignmentToName() {
615 Node parent = getParent();
616 return parent.isAssign()
617 && parent.getFirstChild() == nameNode;
618 }
619
620 boolean isLvalue() {
621 Node parent = getParent();
622 int parentType = parent.getType();
623 return (parentType == Token.VAR && nameNode.getFirstChild() != null)
624 || parentType == Token.INC
625 || parentType == Token.DEC
626 || (NodeUtil.isAssignmentOp(parent)
627 && parent.getFirstChild() == nameNode)
628 || isLhsOfForInExpression(nameNode);
629 }
630
631 Scope getScope() {
632 return scope;
633 }
634 }
635
636 /**
637 * Represents a section of code that is uninterrupted by control structures
638 * (conditional or iterative logic).
639 */
640 static final class BasicBlock {
641
642 private final BasicBlock parent;
643
644 /**
645 * Determines whether the block may not be part of the normal control flow,
646 * but instead "hoisted" to the top of the scope.
647 */
648 private final boolean isHoisted;
649
650 /**
651 * Whether this block denotes a function scope.
652 */
653 private final boolean isFunction;
654
655 /**
656 * Whether this block denotes a loop.
657 */
658 private final boolean isLoop;
659
660 /**
661 * Creates a new block.
662 * @param parent The containing block.
663 * @param root The root node of the block.
664 */
665 BasicBlock(BasicBlock parent, Node root) {
666 this.parent = parent;
667
668 // only named functions may be hoisted.
669 this.isHoisted = NodeUtil.isHoistedFunctionDeclaration(root);
670
671 this.isFunction = root.isFunction();
672
673 if (root.getParent() != null) {
674 int pType = root.getParent().getType();
675 this.isLoop = pType == Token.DO ||
676 pType == Token.WHILE ||
677 pType == Token.FOR;
678 } else {
679 this.isLoop = false;
680 }
681 }
682
683 BasicBlock getParent() {
684 return parent;
685 }
686
687 /**
688 * Determines whether this block is equivalent to the very first block that
689 * is created when reference collection traversal enters global scope. Note
690 * that when traversing a single script in a hot-swap fashion a new instance
691 * of {@code BasicBlock} is created.
692 *
693 * @return true if this is global scope block.
694 */
695 boolean isGlobalScopeBlock() {
696 return getParent() == null;
697 }
698
699 /**
700 * Determines whether this block is guaranteed to begin executing before
701 * the given block does.
702 */
703 boolean provablyExecutesBefore(BasicBlock thatBlock) {
704 // If thatBlock is a descendant of this block, and there are no hoisted
705 // blocks between them, then this block must start before thatBlock.
706 BasicBlock currentBlock;
707 for (currentBlock = thatBlock;
708 currentBlock != null && currentBlock != this;
709 currentBlock = currentBlock.getParent()) {
710 if (currentBlock.isHoisted) {
711 return false;
712 }
713 }
714
715 if (currentBlock == this) {
716 return true;
717 }
718 if (isGlobalScopeBlock() && thatBlock.isGlobalScopeBlock()) {
719 return true;
720 }
721 return false;
722 }
723 }
724 }