-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
NameAnalyzer.java
2014 lines (1809 loc) · 66 KB
/
NameAnalyzer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2006 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Ordering;
import com.google.common.io.Files;
import com.google.javascript.jscomp.CodingConvention.SubclassRelationship;
import com.google.javascript.jscomp.GatherSideEffectSubexpressionsCallback.GetReplacementSideEffectSubexpressions;
import com.google.javascript.jscomp.GatherSideEffectSubexpressionsCallback.SideEffectAccumulator;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.jscomp.NodeTraversal.Callback;
import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge;
import com.google.javascript.jscomp.graph.DiGraph.DiGraphNode;
import com.google.javascript.jscomp.graph.LinkedDirectedGraph;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import java.io.File;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* This pass identifies all global names, simple (e.g. <code>a</code>) or
* qualified (e.g. <code>a.b.c</code>), and the dependencies between them, then
* removes code associated with unreferenced names. It starts by assuming that
* only externally accessible names (e.g. <code>window</code>) are referenced,
* then iteratively marks additional names as referenced (e.g. <code>Foo</code>
* in <code>window['foo'] = new Foo();</code>). This makes it possible to
* eliminate code containing circular references.
*
* <p>Qualified names can be defined using dotted or object literal syntax
* (<code>a.b.c = x;</code> or <code>a.b = {c: x};</code>, respectively).
*
* <p>Removal of prototype classes is currently all or nothing. In other words,
* prototype properties and methods are never individually removed.
*
* <p>Optionally generates pretty HTML output of data so that it is easy to
* analyze dependencies.
*
* <p>Only operates on names defined in the global scope, but it would be easy
* to extend the pass to names defined in local scopes.
*
* TODO(nicksantos): In the initial implementation of this pass, it was
* important to understand namespaced names (e.g., that a.b is distinct from
* a.b.c). Now that this pass comes after CollapseProperties, this is no longer
* necessary. For now, I've changed so that {@code referenceParentNames}
* creates a two-way reference between a.b and a.b.c, so that they're
* effectively the same name. When someone has the time, we should completely
* rip out all the logic that understands namespaces.
*
*/
final class NameAnalyzer implements CompilerPass {
/** Reference to the JS compiler */
private final AbstractCompiler compiler;
/** Map of all JS names found */
private final Map<String, JsName> allNames = new HashMap<>();
/** Reference dependency graph */
private LinkedDirectedGraph<JsName, RefType> referenceGraph =
LinkedDirectedGraph.createWithoutAnnotations();
/**
* Map of name scopes - all children of the Node key have a dependency on the
* name value.
*
* If scopes.get(node).equals(name) && node2 is a child of node, then node2
* will not get executed unless name is referenced via a get operation
*/
private final ListMultimap<Node, NameInformation> scopes =
LinkedListMultimap.create();
/** Used to parse prototype names */
private static final String PROTOTYPE_SUBSTRING = ".prototype.";
private static final int PROTOTYPE_SUBSTRING_LEN =
PROTOTYPE_SUBSTRING.length();
private static final int PROTOTYPE_SUFFIX_LEN = ".prototype".length();
/** Window root */
private static final String WINDOW = "window";
/** Function class name */
private static final String FUNCTION = "Function";
/** All of these refer to global scope. These can be moved to config */
static final Set<String> DEFAULT_GLOBAL_NAMES = ImmutableSet.of(
"window", "goog.global");
/** Whether to remove unreferenced variables in main pass */
private final boolean removeUnreferenced;
/** The path of the report file */
private final String reportPath;
/** Names that refer to the global scope */
private final Set<String> globalNames;
/** Ast change helper */
private final AstChangeProxy changeProxy;
/** Names that are externally defined */
private final Set<String> externalNames = new HashSet<>();
/** Name declarations or assignments, in post-order traversal order */
private final List<RefNode> refNodes = new ArrayList<>();
/**
* When multiple names in the global scope point to the same object, we
* call them aliases. Store a map from each alias name to the alias set.
*/
private final Map<String, AliasSet> aliases = new HashMap<>();
static final DiagnosticType REPORT_PATH_IO_ERROR =
DiagnosticType.error("JSC_REPORT_PATH_IO_ERROR",
"Error writing compiler report to {0}:\n{1}");
/**
* All the aliases in a program form a graph, where each global name is
* a node in the graph, and two names are connected if one directly aliases
* the other.
*
* An {@code AliasSet} represents a connected component in that graph. We do
* not explicitly track the graph--we just track the connected components.
*/
private static class AliasSet {
Set<String> names = new HashSet<>();
// Every alias set starts with exactly 2 names.
AliasSet(String name1, String name2) {
names.add(name1);
names.add(name2);
}
}
/**
* Relationship between the two names.
* Currently only two different reference types exists:
* goog.inherits class relations and all other references.
*/
private static enum RefType {
REGULAR,
INHERITANCE,
}
/**
* Class to hold information that can be determined from a node tree about a
* given name
*/
private static class NameInformation {
/** Fully qualified name */
String name;
/** Whether the name is guaranteed to be externally referenceable */
boolean isExternallyReferenceable = false;
/** Whether this name is a prototype function */
boolean isPrototype = false;
/** Name of the prototype class, i.e. "a" if name is "a.prototype.b" */
String prototypeClass = null;
/** Local name of prototype property i.e. "b" if name is "a.prototype.b" */
String prototypeProperty = null;
/** Name of the super class of name */
String superclass = null;
/** Whether this is a call that only affects the class definition */
boolean onlyAffectsClassDef = false;
@Override
public String toString() {
return "NameInformation:" + name;
}
}
/**
* Struct to hold information about a fully qualified JS name
*/
private static class JsName implements Comparable<JsName> {
/** Fully qualified name */
String name;
/** Name of prototype functions attached to this name */
List<String> prototypeNames = new ArrayList<>();
/** Whether this is an externally defined name */
boolean externallyDefined = false;
/** Whether this node is referenced */
boolean referenced = false;
/** Whether the name has descendants that are written to. */
boolean hasWrittenDescendants = false;
/** Whether the name is used in a instanceof check */
boolean hasInstanceOfReference = false;
/** Whether the name is directly set */
boolean hasSetterReference = false;
/**
* Output the node as a string
*
* @return Node as a string
*/
@Override
public String toString() {
StringBuilder out = new StringBuilder();
out.append(name);
if (!prototypeNames.isEmpty()) {
out.append(" (CLASS)\n");
out.append(" - FUNCTIONS: ");
Iterator<String> pIter = prototypeNames.iterator();
while (pIter.hasNext()) {
out.append(pIter.next());
if (pIter.hasNext()) {
out.append(", ");
}
}
}
return out.toString();
}
@Override
public int compareTo(JsName rhs) {
return this.name.compareTo(rhs.name);
}
}
/**
* Interface to get information about and remove unreferenced names.
*/
interface RefNode {
JsName name();
void remove();
}
/**
* Class for nodes that reference a fully-qualified JS name. Fully qualified
* names are of form A or A.B (A.B.C, etc.). References can get the value or
* set the value of the JS name.
*/
private class JsNameRefNode implements RefNode {
/** JsName node for this reference */
JsName name;
/**
* Parent node of the name access
* (ASSIGN, VAR, FUNCTION, OBJECTLIT, or CALL)
*/
Node parent;
/**
* Create a node that refers to a name
*
* @param name The name
* @param node The top node representing the name (GETPROP, NAME, STRING)
*/
JsNameRefNode(JsName name, Node node) {
this.name = name;
this.parent = node.getParent();
}
@Override
public JsName name() {
return name;
}
@Override
public void remove() {
// Setters have VAR, FUNCTION, or ASSIGN parent nodes. CALL parent
// nodes are global refs, and are handled later in this function.
Node containingNode = parent.getParent();
switch (parent.getToken()) {
case VAR:
Preconditions.checkState(parent.hasOneChild());
replaceWithRhs(containingNode, parent);
break;
case FUNCTION:
replaceWithRhs(containingNode, parent);
break;
case ASSIGN:
if (containingNode.isExprResult()) {
replaceWithRhs(containingNode.getParent(), containingNode);
} else {
replaceWithRhs(containingNode, parent);
}
break;
case OBJECTLIT:
// TODO(nicksantos): Come up with a way to remove this.
// If we remove object lit keys, then we will need to also
// create dependency scopes for them.
break;
case EXPR_RESULT:
Preconditions.checkState(isAnalyzableObjectDefinePropertiesDefinition(parent.getFirstChild()));
replaceWithRhs(containingNode, parent);
break;
default:
throw new IllegalArgumentException(
"Unsupported parent node type in JsNameRefNode.remove: " + parent.getToken());
}
}
}
/**
* Class for nodes that set prototype properties or methods.
*/
private class PrototypeSetNode extends JsNameRefNode {
/**
* Create a set node from the name & setter node
*
* @param name The name
* @param parent Parent node that assigns the expression (an ASSIGN)
*/
PrototypeSetNode(JsName name, Node parent) {
super(name, parent.getFirstChild());
Preconditions.checkState(parent.isAssign());
}
@Override public void remove() {
Node grandparent = parent.getParent();
if (grandparent.isExprResult()) {
// name.prototype.foo = function() { ... };
changeProxy.removeChild(grandparent.getParent(), grandparent);
} else {
// ... name.prototype.foo = function() { ... } ...
changeProxy.replaceWith(grandparent, parent,
parent.getLastChild().detach());
}
}
}
/**
* Base class for special reference nodes.
*/
private abstract static class SpecialReferenceNode implements RefNode {
/** JsName node for the function */
JsName name;
/** The CALL node */
Node node;
/**
* Create a special reference node.
*
* @param name The name
* @param node The CALL node
*/
SpecialReferenceNode(JsName name, Node node) {
this.name = name;
this.node = node;
}
@Override
public JsName name() {
return name;
}
Node getParent() {
return node.getParent();
}
Node getGrandparent() {
return node.getParent() == null ? null : node.getGrandparent();
}
}
/**
* Class for nodes that are function calls that may change a function's
* prototype
*/
private class ClassDefiningFunctionNode extends SpecialReferenceNode {
/**
* Create a class defining function node from the name & setter node
*
* @param name The name
* @param node The CALL node
*/
ClassDefiningFunctionNode(JsName name, Node node) {
super(name, node);
Preconditions.checkState(node.isCall());
}
@Override
public void remove() {
Preconditions.checkState(node.isCall());
Node parent = getParent();
if (parent.isExprResult()) {
changeProxy.removeChild(getGrandparent(), parent);
} else {
changeProxy.replaceWith(parent, node, IR.voidNode(IR.number(0)));
}
}
}
/**
* Class for nodes that check instanceof
*/
private class InstanceOfCheckNode extends SpecialReferenceNode {
/**
* Create an instanceof node from the name and parent node
*
* @param name The name
* @param node The qualified name node
*/
InstanceOfCheckNode(JsName name, Node node) {
super(name, node);
Preconditions.checkState(node.isQualifiedName());
Preconditions.checkState(getParent().isInstanceOf());
}
@Override
public void remove() {
changeProxy.replaceWith(getGrandparent(), getParent(), IR.falseNode());
}
}
/**
* Walk through externs and mark nodes as externally declared if declared
*/
private class ProcessExternals extends AbstractPostOrderCallback {
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
NameInformation ns = null;
if (NodeUtil.isVarDeclaration(n)) {
ns = createNameInformation(t, n);
} else if (NodeUtil.isFunctionDeclaration(n)) {
ns = createNameInformation(t, n.getFirstChild());
}
if (ns != null) {
JsName jsName = getName(ns.name, true);
jsName.externallyDefined = true;
externalNames.add(ns.name);
}
}
}
/**
* <p>Identifies all dependency scopes.
*
* <p>A dependency scope is a relationship between a node tree and a name that
* implies that the node tree will not execute (and thus can be eliminated) if
* the name is never referenced.
*
* <p>The entire parse tree is ultimately in a dependency scope relationship
* with <code>window</code> (or an equivalent name for the global scope), but
* the goal here is to find finer-grained relationships. This callback creates
* dependency scopes for every assignment statement, variable declaration, and
* function call in the global scope.
*
* <p>Note that dependency scope node trees aren't necessarily disjoint.
* In the following code snippet, for example, the function definition
* forms a dependency scope with the name <code>f</code> and the assignment
* inside the function forms a dependency scope with the name <code>x</code>.
* <pre>
* var x; function f() { x = 1; }
* </pre>
*/
private class FindDependencyScopes extends AbstractPostOrderCallback {
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (!t.inGlobalHoistScope()) {
return;
}
if (n.isAssign()) {
recordAssignment(t, n, n);
if (!NodeUtil.isImmutableResult(n.getLastChild())) {
recordConsumers(t, n, n);
}
} else if (NodeUtil.isVarDeclaration(n)) {
NameInformation ns = createNameInformation(t, n);
recordDepScope(n, ns);
} else if (NodeUtil.isFunctionDeclaration(n) && t.inGlobalScope()) {
NameInformation ns = createNameInformation(t, n.getFirstChild());
recordDepScope(n, ns);
} else if (NodeUtil.isExprCall(n)) {
Node callNode = n.getFirstChild();
Node nameNode = callNode.getFirstChild();
NameInformation ns = createNameInformation(t, nameNode);
if (ns != null && ns.onlyAffectsClassDef) {
recordDepScope(n, ns);
}
} else if (isAnalyzableObjectDefinePropertiesDefinition(n)) {
Node targetObject = n.getSecondChild();
NameInformation ns = createNameInformation(t, targetObject);
recordDepScope(n, ns);
}
}
private void recordConsumers(NodeTraversal t, Node n, Node recordNode) {
Node parent = n.getParent();
switch (parent.getToken()) {
case ASSIGN:
if (n == parent.getLastChild()) {
recordAssignment(t, parent, recordNode);
}
recordConsumers(t, parent, recordNode);
break;
case NAME:
NameInformation ns = createNameInformation(t, parent);
recordDepScope(recordNode, ns);
break;
case OR:
recordConsumers(t, parent, recordNode);
break;
case AND:
// In "a && b" only "b" can be meaningfully aliased.
// "a" must be falsy, which it must be an immutable, non-Object
case COMMA:
case HOOK:
if (n != parent.getFirstChild()) {
recordConsumers(t, parent, recordNode);
}
break;
default:
break;
}
}
private void recordAssignment(NodeTraversal t, Node n, Node recordNode) {
Node nameNode = n.getFirstChild();
Node parent = n.getParent();
NameInformation ns = createNameInformation(t, nameNode);
if (ns != null) {
if (parent.isVanillaFor()) {
// Patch for assignments that appear in the init,
// condition or iteration part of a FOR loop. Without
// this change, all 3 of those parts try to claim the for
// loop as their dependency scope. The last assignment in
// those three fields wins, which can result in incorrect
// reference edges between referenced and assigned variables.
//
// TODO(user) revisit the dependency scope calculation
// logic.
if (parent.getSecondChild() != n) {
recordDepScope(recordNode, ns);
} else {
recordDepScope(nameNode, ns);
}
} else if (!parent.isCall() || n != parent.getFirstChild()) {
// The rhs of the assignment is the caller, so it's used by the
// context. Don't associate it w/ the lhs.
// FYI: this fixes only the specific case where the assignment is the
// caller expression, but it could be nested deeper in the caller and
// we would still get a bug.
// See testAssignWithCall2 for an example of this.
recordDepScope(recordNode, ns);
}
}
}
/**
* Defines a dependency scope.
*/
private void recordDepScope(Node node, NameInformation name) {
Preconditions.checkNotNull(name);
scopes.put(node, name);
}
}
/**
* Create JsName objects for variable and function declarations in
* the global scope before computing name references. In JavaScript
* it is legal to refer to variable and function names before the
* actual declaration.
*/
private class HoistVariableAndFunctionDeclarations
extends NodeTraversal.AbstractShallowCallback {
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (NodeUtil.isVarDeclaration(n)) {
NameInformation ns = createNameInformation(t, n);
Preconditions.checkNotNull(ns, "NameInformation is null");
createName(ns.name);
} else if (NodeUtil.isFunctionDeclaration(n)) {
Node nameNode = n.getFirstChild();
NameInformation ns = createNameInformation(t, nameNode);
Preconditions.checkNotNull(ns, "NameInformation is null");
createName(nameNode.getString());
}
}
}
/**
* Identifies all declarations of global names and setter statements
* affecting global symbols (assignments to global names).
*
* All declarations and setters must be gathered in a single
* traversal and stored in traversal order so "removeUnreferenced"
* can perform modifications in traversal order.
*/
private class FindDeclarationsAndSetters extends AbstractPostOrderCallback {
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
// Record global variable and function declarations
if (t.inGlobalHoistScope()) {
if (NodeUtil.isVarDeclaration(n)) {
NameInformation ns = createNameInformation(t, n);
Preconditions.checkNotNull(ns);
recordSet(ns.name, n);
} else if (NodeUtil.isFunctionDeclaration(n) && t.inGlobalScope()) {
Node nameNode = n.getFirstChild();
NameInformation ns = createNameInformation(t, nameNode);
if (ns != null) {
JsName nameInfo = getName(nameNode.getString(), true);
recordSet(nameInfo.name, nameNode);
}
} else if (NodeUtil.isObjectLitKey(n)) {
NameInformation ns = createNameInformation(t, n);
if (ns != null) {
recordSet(ns.name, n);
}
}
}
// Record assignments and call sites
if (n.isAssign() || isAnalyzableObjectDefinePropertiesDefinition(n)) {
Node nameNode = n.isAssign() ? n.getFirstChild() : n;
NameInformation ns = createNameInformation(t, nameNode);
if (ns != null) {
if (ns.isPrototype) {
recordPrototypeSet(ns.prototypeClass, ns.prototypeProperty, n);
} else {
recordSet(ns.name, nameNode);
}
}
} else if (n.isCall()) {
Node nameNode = n.getFirstChild();
NameInformation ns = createNameInformation(t, nameNode);
if (ns != null && ns.onlyAffectsClassDef) {
JsName name = getName(ns.name, true);
refNodes.add(new ClassDefiningFunctionNode(name, n));
}
}
}
/**
* Records the assignment of a value to a global name.
*
* @param name Fully qualified name
* @param node The top node representing the name (GETPROP, NAME, STRING [objlit key],
* or CALL [Object.defineProperties])
*/
private void recordSet(String name, Node node) {
JsName jsn = getName(name, true);
JsNameRefNode nameRefNode = new JsNameRefNode(jsn, node);
refNodes.add(nameRefNode);
jsn.hasSetterReference = true;
// Now, look at all parent names and record that their properties have
// been written to.
if (node.isGetElem() || isAnalyzableObjectDefinePropertiesDefinition(node)) {
recordWriteOnProperties(name);
} else if (name.indexOf('.') != -1) {
recordWriteOnProperties(name.substring(0, name.lastIndexOf('.')));
}
}
/**
* Records the assignment to a prototype property of a global name,
* if possible.
*
* @param className The name of the class.
* @param prototypeProperty The name of the prototype property.
* @param node The top node representing the name (GETPROP)
*/
private void recordPrototypeSet(String className, String prototypeProperty,
Node node) {
JsName name = getName(className, true);
name.prototypeNames.add(prototypeProperty);
refNodes.add(new PrototypeSetNode(name, node));
recordWriteOnProperties(className);
}
/**
* Record that the properties of this name have been written to.
*/
private void recordWriteOnProperties(String parentName) {
do {
JsName parent = getName(parentName, true);
if (parent.hasWrittenDescendants) {
// If we already recorded this name, then all its parents must
// also be recorded. short-circuit this loop.
return;
} else {
parent.hasWrittenDescendants = true;
}
if (parentName.indexOf('.') == -1) {
return;
}
parentName = parentName.substring(0, parentName.lastIndexOf('.'));
} while(true);
}
}
private static final Predicate<Node> NON_LOCAL_RESULT_PREDICATE =
new Predicate<Node>() {
@Override
public boolean apply(Node input) {
if (input.isCall()) {
return false;
}
// TODO(johnlenz): handle NEW calls that record their 'this'
// in global scope and effectively return an alias.
// Other non-local references are handled by this pass.
return true;
}
};
/**
* <p>Identifies all references between global names.
*
* <p>A reference from a name <code>f</code> to a name <code>g</code> means
* that if the name <code>f</code> must be defined, then the name
* <code>g</code> must also be defined. This would be the case if, for
* example, <code>f</code> were a function that called <code>g</code>.
*/
private class FindReferences implements Callback {
Set<Node> nodesToKeep;
FindReferences() {
nodesToKeep = new HashSet<>();
}
private void addAllChildren(Node n) {
nodesToKeep.add(n);
for (Node child = n.getFirstChild();
child != null;
child = child.getNext()) {
addAllChildren(child);
}
}
private void addSimplifiedChildren(Node n) {
NodeTraversal.traverseEs6(
compiler, n, new GatherSideEffectSubexpressionsCallback(compiler, new NodeAccumulator()));
}
private void addSimplifiedExpression(Node n, Node parent) {
if (parent.isVar()) {
Node value = n.getFirstChild();
if (value != null) {
addSimplifiedChildren(value);
}
} else if (n.isAssign()
&& (parent.isExprResult()
|| parent.isVanillaFor()
|| parent.isReturn())) {
for (Node child : n.children()) {
addSimplifiedChildren(child);
}
} else if (isAnalyzableObjectDefinePropertiesDefinition(n)) {
addSimplifiedChildren(n.getLastChild());
} else if (n.isCall() && parent.isExprResult()) {
addSimplifiedChildren(n);
} else {
addAllChildren(n);
}
}
@Override
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
if (parent == null) {
return true;
}
// Gather the list of nodes that either have side effects, are
// arguments to function calls with side effects or are used in
// control structure predicates. These names are always
// referenced when the enclosing function is called.
if (n.isVanillaFor()) {
Node decl = n.getFirstChild();
Node pred = decl.getNext();
Node step = pred.getNext();
addSimplifiedExpression(decl, n);
addSimplifiedExpression(pred, n);
addSimplifiedExpression(step, n);
} else if (n.isForIn()) {
Node decl = n.getFirstChild();
Node iter = decl.getNext();
addAllChildren(decl);
addAllChildren(iter);
}
if (parent.isVar() ||
parent.isExprResult() ||
parent.isReturn() ||
parent.isThrow()) {
addSimplifiedExpression(n, parent);
}
if ((parent.isIf() ||
parent.isWhile() ||
parent.isWith() ||
parent.isSwitch() ||
parent.isCase()) &&
parent.getFirstChild() == n) {
addAllChildren(n);
}
if (parent.isDo() && parent.getLastChild() == n) {
addAllChildren(n);
}
return true;
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (!n.isName() && (!NodeUtil.isGet(n) || parent.isGetProp())) {
// This is not a simple or qualified name.
return;
}
NameInformation nameInfo = createNameInformation(t, n);
if (nameInfo == null) {
// The name is not a global name
return;
}
if (nameInfo.onlyAffectsClassDef) {
if (nameInfo.superclass != null) {
recordReference(
nameInfo.name, nameInfo.superclass, RefType.INHERITANCE);
}
// Make sure that we record a reference to the function that does
// the inheritance, so that the inherits() function itself does
// not get stripped.
String nodeName = n.getQualifiedName();
if (nodeName != null) {
recordReference(
nameInfo.name, nodeName, RefType.REGULAR);
}
return;
}
// instanceof checks are not handled like regular read references.
boolean isInstanceOfCheck = parent.isInstanceOf() &&
parent.getLastChild() == n;
if (isInstanceOfCheck) {
JsName checkedClass = getName(nameInfo.name, true);
// If we know where this constructor is created, and we
// know we can find all 'new' calls on it, then treat
// this as a special reference. It will be replaced with
// false if there are no other references, because we
// know the class can't be instantiated.
if (checkedClass.hasSetterReference &&
!nameInfo.isExternallyReferenceable &&
// Exclude GETELEMs.
n.isQualifiedName()) {
refNodes.add(new InstanceOfCheckNode(checkedClass, n));
checkedClass.hasInstanceOfReference = true;
return;
}
}
// Determine which name might be potentially referring to this one by
// looking up the nearest enclosing dependency scope. It's unnecessary to
// determine all enclosing dependency scopes because this callback should
// create a chain of references between them.
List<NameInformation> referers = getDependencyScope(n);
if (referers.isEmpty()) {
maybeRecordReferenceOrAlias(t, n, parent, nameInfo, null);
} else {
for (NameInformation referring : referers) {
maybeRecordReferenceOrAlias(t, n, parent, nameInfo, referring);
}
recordAliases(referers);
}
}
private void maybeRecordReferenceOrAlias(
NodeTraversal t, Node n, Node parent,
NameInformation nameInfo, NameInformation referring) {
String referringName = "";
if (referring != null) {
referringName = referring.isPrototype
? referring.prototypeClass
: referring.name;
}
String name = nameInfo.name;
// A value whose result is the return value of a function call
// can be an alias to global object.
// Here we add an alias to the general "global" object
// to act as a placeholder for the actual (unnamed) value.
if (maybeHiddenAlias(n)) {
recordAlias(name, WINDOW);
}
// An externally referenceable name must always be defined, so we add a
// reference to it from the global scope (a.k.a. window).
if (nameInfo.isExternallyReferenceable) {
recordReference(WINDOW, name, RefType.REGULAR);
maybeRecordAlias(name, parent, referring, referringName);
return;
}
// An assignment implies a reference from the enclosing dependency scope.
// For example, foo references bar in: function foo() {bar=5}.
if (NodeUtil.isVarOrSimpleAssignLhs(n, parent)) {
if (referring != null) {
recordReference(referringName, name, RefType.REGULAR);
}
return;
}
if (nodesToKeep.contains(n)) {
List<NameInformation> functionScopes =
getEnclosingFunctionDependencyScope(t);
if (!functionScopes.isEmpty()) {
for (NameInformation functionScope : functionScopes) {
recordReference(functionScope.name, name, RefType.REGULAR);
}
} else {
recordReference(WINDOW, name, RefType.REGULAR);
if (referring != null) {
maybeRecordAlias(name, parent, referring, referringName);
}
}
} else if (referring != null) {
if (!maybeRecordAlias(name, parent, referring, referringName)) {
RefType depType = referring.onlyAffectsClassDef ?
RefType.INHERITANCE : RefType.REGULAR;
recordReference(referringName, name, depType);
}
} else {
// No named dependency scope found. Unfortunately that might
// mean that the expression is a child of an function expression
// or assignment with a complex lhs. In those cases,
// protect this node by creating a reference to WINDOW.
for (Node ancestor : n.getAncestors()) {
if (NodeUtil.isAssignmentOp(ancestor) ||
ancestor.isFunction()) {
recordReference(WINDOW, name, RefType.REGULAR);
break;
}
}
}
}
private void recordAliases(List<NameInformation> referers) {
int size = referers.size();
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
recordAlias(referers.get(i).name, referers.get(j).name);
recordAlias(referers.get(j).name, referers.get(i).name);
}