-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
NewTypeInference.java
4421 lines (4179 loc) · 170 KB
/
NewTypeInference.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 2013 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 com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import com.google.javascript.jscomp.CodingConvention.AssertionFunctionSpec;
import com.google.javascript.jscomp.CodingConvention.Bind;
import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge;
import com.google.javascript.jscomp.graph.DiGraph.DiGraphNode;
import com.google.javascript.jscomp.newtypes.DeclaredFunctionType;
import com.google.javascript.jscomp.newtypes.FunctionType;
import com.google.javascript.jscomp.newtypes.FunctionTypeBuilder;
import com.google.javascript.jscomp.newtypes.JSType;
import com.google.javascript.jscomp.newtypes.JSTypes;
import com.google.javascript.jscomp.newtypes.MismatchInfo;
import com.google.javascript.jscomp.newtypes.NominalType;
import com.google.javascript.jscomp.newtypes.QualifiedName;
import com.google.javascript.jscomp.newtypes.TypeEnv;
import com.google.javascript.jscomp.newtypes.UniqueNameGenerator;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.TypeI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* New type inference algorithm.
*
* Main differences from the old type checker:
* - Infers types for unannotated functions
* - Stricter with missing-property warnings
* - Stricter when checking the operands of primitive operators
* - Requires constants to be typed
* - Tries to warn about misplaced annotations, rather than silently ignore them
*
* @author blickly@google.com (Ben Lickly)
* @author dimvar@google.com (Dimitris Vardoulakis)
*
*/
final class NewTypeInference implements CompilerPass {
static final DiagnosticType MISTYPED_ASSIGN_RHS = DiagnosticType.warning(
"JSC_NTI_MISTYPED_ASSIGN_RHS",
"The right side in the assignment is not a subtype of the left side.\n"
+ "{0}");
static final DiagnosticType INVALID_OPERAND_TYPE = DiagnosticType.warning(
"JSC_NTI_INVALID_OPERAND_TYPE",
"Invalid type(s) for operator {0}.\n"
+ "{1}");
static final DiagnosticType RETURN_NONDECLARED_TYPE = DiagnosticType.warning(
"JSC_NTI_RETURN_NONDECLARED_TYPE",
"Returned type does not match declared return type.\n"
+ "{0}");
static final DiagnosticType INVALID_INFERRED_RETURN_TYPE =
DiagnosticType.warning(
"JSC_NTI_INVALID_INFERRED_RETURN_TYPE",
"Function called in context that expects incompatible type.\n"
+ "{0}");
static final DiagnosticType INVALID_ARGUMENT_TYPE = DiagnosticType.warning(
"JSC_NTI_INVALID_ARGUMENT_TYPE",
"Invalid type for parameter {0} of function {1}.\n"
+ "{2}");
static final DiagnosticType CROSS_SCOPE_GOTCHA = DiagnosticType.warning(
"JSC_NTI_CROSS_SCOPE_GOTCHA",
"Variable {0} typed inconsistently across scopes.\n" +
"In outer scope : {1}\n" +
"In inner scope : {2}\n");
static final DiagnosticType POSSIBLY_INEXISTENT_PROPERTY =
DiagnosticType.warning(
"JSC_NTI_POSSIBLY_INEXISTENT_PROPERTY",
"Property {0} may not be present on {1}.");
static final DiagnosticType PROPERTY_ACCESS_ON_NONOBJECT =
DiagnosticType.warning(
"JSC_NTI_PROPERTY_ACCESS_ON_NONOBJECT",
"Cannot access property {0} of non-object type {1}.");
static final DiagnosticType NOT_UNIQUE_INSTANTIATION =
DiagnosticType.warning(
"JSC_NTI_NOT_UNIQUE_INSTANTIATION",
"When instantiating a polymorphic function,"
+ " you can only specify one type for each type variable.\n"
+ " Found {0} types for type variable {1}: {2},\n"
+ " when instantiating type: {3}");
static final DiagnosticType FAILED_TO_UNIFY =
DiagnosticType.warning(
"JSC_NTI_FAILED_TO_UNIFY",
"Could not instantiate type {0} with {1}.");
static final DiagnosticType INVALID_INDEX_TYPE =
DiagnosticType.warning(
"JSC_NTI_INVALID_INDEX_TYPE",
"Invalid type for index.\n"
+ "{0}");
static final DiagnosticType BOTTOM_INDEX_TYPE =
DiagnosticType.warning(
"JSC_NTI_BOTTOM_INDEX_TYPE",
"This IObject {0} cannot be accessed with a valid type.\n"
+ " Usually the result of a bad union type.\n");
static final DiagnosticType INVALID_OBJLIT_PROPERTY_TYPE =
DiagnosticType.warning(
"JSC_NTI_INVALID_OBJLIT_PROPERTY_TYPE",
"Invalid type for object-literal property.\n"
+ "{0}");
static final DiagnosticType FORIN_EXPECTS_OBJECT =
DiagnosticType.warning(
"JSC_NTI_FORIN_EXPECTS_OBJECT",
"For/in expects an object, found type {0}.");
static final DiagnosticType FORIN_EXPECTS_STRING_KEY =
DiagnosticType.warning(
"JSC_NTI_FORIN_EXPECTS_STRING_KEY",
"For/in creates string keys, but variable has declared type {1}.");
static final DiagnosticType CONST_REASSIGNED =
DiagnosticType.warning(
"JSC_NTI_CONST_REASSIGNED",
"Cannot change the value of a constant.");
static final DiagnosticType CONST_PROPERTY_REASSIGNED =
DiagnosticType.warning(
"JSC_NTI_CONST_PROPERTY_REASSIGNED",
"Cannot change the value of a constant property.");
static final DiagnosticType CONST_PROPERTY_DELETED =
DiagnosticType.warning(
"JSC_NTI_CONSTANT_PROPERTY_DELETED",
"Constant property {0} cannot be deleted");
static final DiagnosticType NOT_A_CONSTRUCTOR =
DiagnosticType.warning(
"JSC_NTI_NOT_A_CONSTRUCTOR",
"Expected a constructor but found type {0}.");
static final DiagnosticType CANNOT_INSTANTIATE_ABSTRACT_CLASS =
DiagnosticType.warning(
"JSC_NTI_CANNOT_INSTANTIATE_ABSTRACT_CLASS",
"Cannot instantiate abstract class {0}.");
static final DiagnosticType UNDEFINED_SUPER_CLASS =
DiagnosticType.warning(
"JSC_UNDEFINED_SUPER_CLASS",
"Undefined super class for {0}.");
static final DiagnosticType ASSERT_FALSE =
DiagnosticType.warning(
"JSC_NTI_ASSERT_FALSE",
"Assertion is always false. Please use a throw or fail() instead.");
static final DiagnosticType UNKNOWN_ASSERTION_TYPE =
DiagnosticType.warning(
"JSC_NTI_UNKNOWN_ASSERTION_TYPE",
"Assert with unknown asserted type.");
static final DiagnosticType INVALID_THIS_TYPE_IN_BIND =
DiagnosticType.warning(
"JSC_NTI_INVALID_THIS_TYPE_IN_BIND",
"Invalid type for the first argument to bind.\n"
+ "{0}");
static final DiagnosticType CANNOT_BIND_CTOR =
DiagnosticType.warning(
"JSC_NTI_CANNOT_BIND_CTOR",
"We do not support using .bind on constructor functions.");
static final DiagnosticType GOOG_BIND_EXPECTS_FUNCTION =
DiagnosticType.warning(
"JSC_NTI_GOOG_BIND_EXPECTS_FUNCTION",
"The first argument to goog.bind/goog.partial must be a function,"
+ " found: {0}");
static final DiagnosticType BOTTOM_PROP =
DiagnosticType.warning(
"JSC_NTI_BOTTOM_PROP",
"Property {0} of {1} cannot have a valid type."
+ "Maybe the result of a union of incompatible types?");
static final DiagnosticType INVALID_CAST =
DiagnosticType.warning("JSC_NTI_INVALID_CAST",
"invalid cast - the types do not have a common subtype\n" +
"from: {0}\n" +
"to : {1}");
static final DiagnosticType GLOBAL_THIS = DiagnosticType.warning(
"JSC_NTI_USED_GLOBAL_THIS",
"Dangerous use of the global THIS object");
static final DiagnosticType MISSING_RETURN_STATEMENT =
DiagnosticType.warning(
"JSC_NTI_MISSING_RETURN_STATEMENT",
"Missing return statement. Function expected to return {0}.");
static final DiagnosticType CONSTRUCTOR_NOT_CALLABLE =
DiagnosticType.warning(
"JSC_NTI_CONSTRUCTOR_NOT_CALLABLE",
"Constructor {0} should be called with the \"new\" keyword");
static final DiagnosticType ILLEGAL_OBJLIT_KEY =
DiagnosticType.warning(
"JSC_NTI_ILLEGAL_OBJLIT_KEY",
"Illegal key, the object literal is a {0}");
static final DiagnosticType ILLEGAL_PROPERTY_CREATION =
DiagnosticType.warning(
"JSC_NTI_ILLEGAL_PROPERTY_CREATION",
"Cannot add property {0} to a struct instance after it is constructed.");
static final DiagnosticType IN_USED_WITH_STRUCT =
DiagnosticType.warning(
"JSC_NTI_IN_USED_WITH_STRUCT",
"Cannot use the IN operator with structs");
static final DiagnosticType ADDING_PROPERTY_TO_NON_OBJECT =
DiagnosticType.warning(
"JSC_NTI_ADDING_PROPERTY_TO_NON_OBJECT",
"Cannot create property {0} on non-object type {1}.");
public static final DiagnosticType INEXISTENT_PROPERTY =
DiagnosticType.warning(
"JSC_NTI_INEXISTENT_PROPERTY",
"Property {0} never defined on {1}");
static final DiagnosticType NOT_CALLABLE =
DiagnosticType.warning(
"JSC_NTI_NOT_FUNCTION_TYPE",
"Cannot call non-function type {0}");
static final DiagnosticType WRONG_ARGUMENT_COUNT =
DiagnosticType.warning(
"JSC_NTI_WRONG_ARGUMENT_COUNT",
"Function {0}: called with {1} argument(s). " +
"Function requires at least {2} argument(s){3}.");
static final DiagnosticType ILLEGAL_PROPERTY_ACCESS =
DiagnosticType.warning(
"JSC_NTI_ILLEGAL_PROPERTY_ACCESS",
"Cannot do {0} access on a {1}");
static final DiagnosticType UNKNOWN_TYPEOF_VALUE =
DiagnosticType.warning(
"JSC_NTI_UNKNOWN_TYPEOF_VALUE",
"unknown type: {0}");
static final DiagnosticType UNKNOWN_NAMESPACE_PROPERTY =
DiagnosticType.warning(
"JSC_NTI_UNKNOWN_NAMESPACE_PROPERTY",
"Cannot determine the type of namespace property {0}. "
+ "Maybe a prefix of the property name has been redefined?");
static final DiagnosticType INCOMPATIBLE_STRICT_COMPARISON =
DiagnosticType.warning(
"JSC_INCOMPATIBLE_STRICT_COMPARISON",
"Cannot perform strict equality / inequality comparisons on incompatible types:\n"
+ "left : {0}\n"
+ "right: {1}");
static final DiagnosticType ABSTRACT_METHOD_NOT_CALLABLE =
DiagnosticType.warning(
"JSC_NTI_ABSTRACT_METHOD_NOT_CALLABLE",
"Abstract method {0} cannot be called");
// Not part of ALL_DIAGNOSTICS because it should not be enabled with
// --jscomp_error=newCheckTypes. It should only be enabled explicitly.
static final DiagnosticType NULLABLE_DEREFERENCE =
DiagnosticType.disabled(
"JSC_NTI_NULLABLE_DEREFERENCE",
"Attempt to use nullable type {0}.");
static final DiagnosticType UNKNOWN_EXPR_TYPE =
DiagnosticType.disabled(
"JSC_NTI_UNKNOWN_EXPR_TYPE",
"This {0} expression has the unknown type.");
static final DiagnosticGroup COMPATIBLE_DIAGNOSTICS = new DiagnosticGroup(
ABSTRACT_METHOD_NOT_CALLABLE,
ASSERT_FALSE,
CANNOT_BIND_CTOR,
CANNOT_INSTANTIATE_ABSTRACT_CLASS,
CONST_PROPERTY_DELETED,
CONST_PROPERTY_REASSIGNED,
CONST_REASSIGNED,
CONSTRUCTOR_NOT_CALLABLE,
FAILED_TO_UNIFY,
FORIN_EXPECTS_STRING_KEY,
GLOBAL_THIS,
GOOG_BIND_EXPECTS_FUNCTION,
ILLEGAL_OBJLIT_KEY,
ILLEGAL_PROPERTY_ACCESS,
ILLEGAL_PROPERTY_CREATION,
IN_USED_WITH_STRUCT,
INEXISTENT_PROPERTY,
INVALID_ARGUMENT_TYPE,
INVALID_CAST,
INVALID_INDEX_TYPE,
INVALID_OBJLIT_PROPERTY_TYPE,
MISSING_RETURN_STATEMENT,
MISTYPED_ASSIGN_RHS,
NOT_A_CONSTRUCTOR,
NOT_CALLABLE,
POSSIBLY_INEXISTENT_PROPERTY,
RETURN_NONDECLARED_TYPE,
UNKNOWN_ASSERTION_TYPE,
UNKNOWN_TYPEOF_VALUE,
WRONG_ARGUMENT_COUNT);
// TODO(dimvar): Check for which of these warnings it makes sense to keep
// going after warning, eg, for NOT_UNIQUE_INSTANTIATION, we must instantiate
// to the join of the types.
static final DiagnosticGroup NEW_DIAGNOSTICS = new DiagnosticGroup(
ADDING_PROPERTY_TO_NON_OBJECT,
BOTTOM_INDEX_TYPE,
BOTTOM_PROP,
CROSS_SCOPE_GOTCHA,
FORIN_EXPECTS_OBJECT,
INCOMPATIBLE_STRICT_COMPARISON,
INVALID_INFERRED_RETURN_TYPE,
INVALID_OPERAND_TYPE,
INVALID_THIS_TYPE_IN_BIND,
NOT_UNIQUE_INSTANTIATION,
PROPERTY_ACCESS_ON_NONOBJECT,
UNKNOWN_NAMESPACE_PROPERTY);
public static class WarningReporter {
AbstractCompiler compiler;
WarningReporter(AbstractCompiler compiler) { this.compiler = compiler; }
void add(JSError warning) {
String filename = warning.node.getSourceFileName();
// Avoid some warnings in code generated by the ES6 transpilation.
// TODO(dimvar): typecheck that code properly and remove this.
if (filename != null && filename.startsWith(" [synthetic")
|| JSType.mockToString) {
return;
}
compiler.report(warning);
}
}
private WarningReporter warnings;
private final AbstractCompiler compiler;
private final CodingConvention convention;
private Map<DiGraphEdge<Node, ControlFlowGraph.Branch>, TypeEnv> envs;
private Map<NTIScope, JSType> summaries;
private Map<Node, DeferredCheck> deferredChecks;
private ControlFlowGraph<Node> cfg;
private NTIScope currentScope;
// This TypeEnv should be computed once per scope
private TypeEnv typeEnvFromDeclaredTypes = null;
private GlobalTypeInfo symbolTable;
private JSTypes commonTypes;
// RETVAL_ID is used when we calculate the summary type of a function
private static final String RETVAL_ID = "%return";
private static final String THIS_ID = "this";
private final String ABSTRACT_METHOD_NAME;
private final Map<String, AssertionFunctionSpec> assertionFunctionsMap;
// To avoid creating warning objects for disabled warnings
private final boolean reportUnknownTypes;
private final boolean reportNullDeref;
// Fields used in the compatibility mode
private final boolean joinTypesWhenInstantiatingGenerics;
private final boolean allowPropertyOnSubtypes;
private final boolean areTypeVariablesUnknown;
// Used only for development
private static boolean showDebuggingPrints = false;
static boolean measureMem = false;
private static long peakMem = 0;
// Used to avoid typing this.commonTypes.TYPENAME everywhere.
private JSType BOOLEAN;
private JSType BOTTOM;
private JSType FALSE_TYPE;
private JSType FALSY;
private JSType NULL;
private JSType NULL_OR_UNDEFINED;
private JSType NUMBER;
private JSType NUMBER_OR_STRING;
private JSType STRING;
private JSType TOP;
private JSType TOP_OBJECT;
private JSType TRUE_TYPE;
private JSType TRUTHY;
private JSType UNDEFINED;
private JSType UNKNOWN;
NewTypeInference(AbstractCompiler compiler) {
this.warnings = new WarningReporter(compiler);
this.compiler = compiler;
this.convention = compiler.getCodingConvention();
this.envs = new LinkedHashMap<>();
this.summaries = new LinkedHashMap<>();
this.deferredChecks = new LinkedHashMap<>();
this.ABSTRACT_METHOD_NAME = convention.getAbstractMethodName();
this.reportUnknownTypes =
compiler.getOptions().enables(DiagnosticGroups.REPORT_UNKNOWN_TYPES);
this.reportNullDeref = compiler.getOptions()
.enables(DiagnosticGroups.NEW_CHECK_TYPES_ALL_CHECKS);
assertionFunctionsMap = new LinkedHashMap<>();
for (AssertionFunctionSpec assertionFunction : convention.getAssertionFunctions()) {
assertionFunctionsMap.put(
assertionFunction.getFunctionName(),
assertionFunction);
}
boolean inCompatibilityMode =
compiler.getOptions().disables(DiagnosticGroups.NEW_CHECK_TYPES_EXTRA_CHECKS);
this.joinTypesWhenInstantiatingGenerics = inCompatibilityMode;
this.allowPropertyOnSubtypes = inCompatibilityMode;
this.areTypeVariablesUnknown = inCompatibilityMode;
}
@VisibleForTesting // Only used from tests
public NTIScope processForTesting(Node externs, Node root) {
process(externs, root);
return symbolTable.getGlobalScope();
}
@Override
public void process(Node externs, Node root) {
try {
this.symbolTable = (GlobalTypeInfo) compiler.getSymbolTable();
this.commonTypes = symbolTable.getCommonTypes();
this.BOOLEAN = this.commonTypes.BOOLEAN;
this.BOTTOM = this.commonTypes.BOTTOM;
this.FALSE_TYPE = this.commonTypes.FALSE_TYPE;
this.FALSY = this.commonTypes.FALSY;
this.NULL = this.commonTypes.NULL;
this.NULL_OR_UNDEFINED = this.commonTypes.NULL_OR_UNDEFINED;
this.NUMBER = this.commonTypes.NUMBER;
this.NUMBER_OR_STRING = this.commonTypes.NUMBER_OR_STRING;
this.STRING = this.commonTypes.STRING;
this.TOP = this.commonTypes.TOP;
this.TOP_OBJECT = this.commonTypes.getTopObject();
this.TRUE_TYPE = this.commonTypes.TRUE_TYPE;
this.TRUTHY = this.commonTypes.TRUTHY;
this.UNDEFINED = this.commonTypes.UNDEFINED;
this.UNKNOWN = this.commonTypes.UNKNOWN;
for (NTIScope scope : symbolTable.getScopes()) {
analyzeFunction(scope);
envs.clear();
}
for (DeferredCheck check : deferredChecks.values()) {
check.runCheck(summaries, warnings);
}
if (measureMem) {
System.out.println("Peak mem: " + peakMem + "MB");
}
} catch (Exception unexpectedException) {
String message = unexpectedException.getMessage();
if (currentScope != null) {
message += "\nIn scope: " + currentScope;
}
this.compiler.throwInternalError(message, unexpectedException);
}
}
static void updatePeakMem() {
Runtime rt = Runtime.getRuntime();
long currentUsedMem = (rt.totalMemory() - rt.freeMemory()) / (1024 * 1024);
if (currentUsedMem > peakMem) {
peakMem = currentUsedMem;
}
}
private static void println(Object ... objs) {
if (showDebuggingPrints) {
StringBuilder b = new StringBuilder();
for (Object obj : objs) {
b.append(obj);
}
System.out.println(b);
}
}
private TypeEnv getInEnv(DiGraphNode<Node, ControlFlowGraph.Branch> dn) {
List<DiGraphEdge<Node, ControlFlowGraph.Branch>> inEdges = dn.getInEdges();
// True for code considered dead in the CFG
if (inEdges.isEmpty()) {
return getEntryTypeEnv();
}
if (inEdges.size() == 1) {
return envs.get(inEdges.get(0));
}
Set<TypeEnv> envSet = new LinkedHashSet<>();
for (DiGraphEdge<Node, ControlFlowGraph.Branch> de : inEdges) {
TypeEnv env = envs.get(de);
if (env != null) {
envSet.add(env);
}
}
if (envSet.isEmpty()) {
return null;
}
return TypeEnv.join(envSet);
}
private TypeEnv getOutEnv(DiGraphNode<Node, ControlFlowGraph.Branch> dn) {
List<DiGraphEdge<Node, ControlFlowGraph.Branch>> outEdges = dn.getOutEdges();
if (outEdges.isEmpty()) {
// This occurs when visiting a throw in the backward direction.
Preconditions.checkArgument(dn.getValue().isThrow());
return this.typeEnvFromDeclaredTypes;
}
if (outEdges.size() == 1) {
return envs.get(outEdges.get(0));
}
Set<TypeEnv> envSet = new LinkedHashSet<>();
for (DiGraphEdge<Node, ControlFlowGraph.Branch> de : outEdges) {
TypeEnv env = envs.get(de);
if (env != null) {
envSet.add(env);
}
}
Preconditions.checkState(!envSet.isEmpty());
return TypeEnv.join(envSet);
}
private TypeEnv setOutEnv(
DiGraphNode<Node, ControlFlowGraph.Branch> dn, TypeEnv e) {
for (DiGraphEdge<Node, ControlFlowGraph.Branch> de : dn.getOutEdges()) {
envs.put(de, e);
}
return e;
}
// Initialize the type environments on the CFG edges before the FWD analysis.
private void initEdgeEnvsFwd(TypeEnv entryEnv) {
envs.clear();
// For function scopes, add the formal parameters and the free variables
// from outer scopes to the environment.
Set<String> nonLocals = new LinkedHashSet<>();
if (currentScope.hasThis()) {
nonLocals.add(THIS_ID);
}
if (currentScope.isFunction()) {
if (currentScope.getName() != null) {
nonLocals.add(currentScope.getName());
}
nonLocals.addAll(currentScope.getOuterVars());
nonLocals.addAll(currentScope.getFormals());
entryEnv = envPutType(entryEnv, RETVAL_ID, UNDEFINED);
} else {
nonLocals.addAll(currentScope.getExterns());
}
for (String name : nonLocals) {
JSType declType = currentScope.getDeclaredTypeOf(name);
JSType initType = declType;
if (initType == null) {
initType = envGetType(entryEnv, name);
} else if (this.areTypeVariablesUnknown) {
initType = initType.substituteGenericsWithUnknown();
}
println("Adding non-local ", name,
" with decltype: ", declType,
" and inittype: ", initType);
entryEnv = envPutType(entryEnv, name, initType);
}
// For all scopes, add local variables and (local) function definitions
// to the environment.
for (String local : currentScope.getLocals()) {
if (!currentScope.isFunctionNamespace(local)) {
entryEnv = envPutType(entryEnv, local, UNDEFINED);
}
}
for (String fnName : currentScope.getLocalFunDefs()) {
entryEnv = envPutType(entryEnv, fnName, getSummaryOfLocalFunDef(fnName));
}
println("Keeping env: ", entryEnv);
setOutEnv(this.cfg.getEntry(), entryEnv);
}
private TypeEnv getTypeEnvFromDeclaredTypes() {
TypeEnv env = new TypeEnv();
Set<String> varNames = currentScope.getOuterVars();
Set<String> locals = currentScope.getLocals();
varNames.addAll(locals);
varNames.addAll(currentScope.getExterns());
if (currentScope.hasThis()) {
varNames.add(THIS_ID);
}
if (currentScope.isFunction()) {
Node fn = currentScope.getRoot();
if (!currentScope.hasThis() && NodeUtil.referencesSuper(fn)) {
// This function is a static method on some class. To do lookups of the
// class name, we add the root of the qualified name to the environment.
Node funNameNode = NodeUtil.getBestLValue(fn);
Node qnameRoot = NodeUtil.getRootOfQualifiedName(funNameNode);
Preconditions.checkState(qnameRoot.isName());
varNames.add(qnameRoot.getString());
}
if (currentScope.getName() != null) {
varNames.add(currentScope.getName());
}
varNames.addAll(currentScope.getFormals());
// In the rare case when there is a local variable named "arguments",
// this entry will be overwritten in the foreach loop below.
JSType argumentsType;
DeclaredFunctionType dft = currentScope.getDeclaredFunctionType();
if (dft.getOptionalArity() == 0 && dft.hasRestFormals()) {
argumentsType = dft.getRestFormalsType();
} else {
argumentsType = UNKNOWN;
}
env = envPutType(env, "arguments",
commonTypes.getArgumentsArrayType(argumentsType));
}
for (String varName : varNames) {
if (!locals.contains(varName) || !currentScope.isFunctionNamespace(varName)) {
JSType declType = currentScope.getDeclaredTypeOf(varName);
if (declType == null) {
declType = UNKNOWN;
} else if (areTypeVariablesUnknown) {
declType = declType.substituteGenericsWithUnknown();
}
env = envPutType(env, varName, declType);
}
}
for (String fnName : currentScope.getLocalFunDefs()) {
env = envPutType(env, fnName, getSummaryOfLocalFunDef(fnName));
}
return env;
}
private JSType getSummaryOfLocalFunDef(String name) {
NTIScope fnScope = currentScope.getScope(name);
JSType fnType = summaries.get(fnScope);
if (fnType != null) {
return fnType;
}
// Functions defined in externs have no summary, so use the declared type
fnType = currentScope.getDeclaredTypeOf(name);
if (fnType.getFunType() == null) {
// Can happen when a function defined in externs clashes with a variable
// defined by a catch block.
// TODO(dimvar): once we fix scoping for catch blocks, uncomment the
// precondition below.
Preconditions.checkState(fnType.isUnknown());
return this.commonTypes.qmarkFunction();
// Preconditions.checkState(fnType.getFunType() != null,
// "Needed function but found %s", fnType);
}
return changeTypeIfFunctionNamespace(fnScope, fnType);
}
private void buildWorkset(
DiGraphNode<Node, ControlFlowGraph.Branch> dn,
List<DiGraphNode<Node, ControlFlowGraph.Branch>> workset) {
buildWorksetHelper(dn, workset,
new LinkedHashSet<DiGraphNode<Node, ControlFlowGraph.Branch>>());
}
private void buildWorksetHelper(
DiGraphNode<Node, ControlFlowGraph.Branch> dn,
List<DiGraphNode<Node, ControlFlowGraph.Branch>> workset,
Set<DiGraphNode<Node, ControlFlowGraph.Branch>> seen) {
if (seen.contains(dn) || dn == this.cfg.getImplicitReturn()) {
return;
}
switch (dn.getValue().getToken()) {
case DO:
case WHILE:
case FOR:
case FOR_IN:
// Do the loop body first, then the loop follow.
// For DO loops, we do BODY-CONDT-CONDF-FOLLOW
// Since CONDT is currently unused, this could be optimized.
List<DiGraphEdge<Node, ControlFlowGraph.Branch>> outEdges = dn.getOutEdges();
seen.add(dn);
workset.add(dn);
for (DiGraphEdge<Node, ControlFlowGraph.Branch> outEdge : outEdges) {
if (outEdge.getValue() == ControlFlowGraph.Branch.ON_TRUE) {
buildWorksetHelper(outEdge.getDestination(), workset, seen);
}
}
workset.add(dn);
for (DiGraphEdge<Node, ControlFlowGraph.Branch> outEdge : outEdges) {
if (outEdge.getValue() == ControlFlowGraph.Branch.ON_FALSE) {
buildWorksetHelper(outEdge.getDestination(), workset, seen);
}
}
break;
default: {
// Wait for all other incoming edges at join nodes.
for (DiGraphEdge<Node, ControlFlowGraph.Branch> inEdge :
dn.getInEdges()) {
if (!seen.contains(inEdge.getSource())
&& !inEdge.getSource().getValue().isDo()) {
return;
}
}
seen.add(dn);
if (this.cfg.getEntry() != dn) {
workset.add(dn);
}
// Don't recur for straight-line code
while (true) {
Node n = dn.getValue();
if (n.isTry()) {
maybeAddDeadCode(workset, seen, n.getSecondChild());
} else if (n.isBreak() || n.isContinue() || n.isThrow()) {
maybeAddDeadCode(workset, seen, n.getNext());
}
List<DiGraphNode<Node, ControlFlowGraph.Branch>> succs =
this.cfg.getDirectedSuccNodes(dn);
if (succs.size() != 1) {
break;
}
DiGraphNode<Node, ControlFlowGraph.Branch> succ = succs.get(0);
if (succ == this.cfg.getImplicitReturn()) {
if (n.getNext() != null) {
maybeAddDeadCode(workset, seen, n.getNext());
}
return;
}
// Make sure that succ isn't a join node
if (this.cfg.getDirectedPredNodes(succ).size() > 1) {
break;
}
workset.add(succ);
seen.add(succ);
dn = succ;
}
for (DiGraphNode<Node, ControlFlowGraph.Branch> succ :
this.cfg.getDirectedSuccNodes(dn)) {
buildWorksetHelper(succ, workset, seen);
}
break;
}
}
}
// Analyze dead code, such as a catch that is never executed or a statement
// following a return/break/continue. This code can be a predecessor of live
// code in the cfg. We wait on incoming edges before adding nodes to the
// workset, and don't want dead code to block live code from being analyzed.
private void maybeAddDeadCode(
List<DiGraphNode<Node, ControlFlowGraph.Branch>> workset,
Set<DiGraphNode<Node, ControlFlowGraph.Branch>> seen,
Node maybeDeadNode) {
if (maybeDeadNode == null) {
return;
}
DiGraphNode<Node, ControlFlowGraph.Branch> cfgNode =
this.cfg.getDirectedGraphNode(maybeDeadNode);
if (cfgNode == null) {
return;
}
if (this.cfg.getDirectedPredNodes(cfgNode).isEmpty()) {
buildWorksetHelper(cfgNode, workset, seen);
}
}
private void analyzeFunction(NTIScope scope) {
println("=== Analyzing function: ", scope.getReadableName(), " ===");
currentScope = scope;
ControlFlowAnalysis cfa = new ControlFlowAnalysis(compiler, false, false);
cfa.process(null, scope.getRoot());
this.cfg = cfa.getCfg();
println(this.cfg);
// The size is > 1 when multiple files are compiled
// Preconditions.checkState(cfg.getEntry().getOutEdges().size() == 1);
List<DiGraphNode<Node, ControlFlowGraph.Branch>> workset =
new LinkedList<>();
buildWorkset(this.cfg.getEntry(), workset);
/* println("Workset: ", workset); */
this.typeEnvFromDeclaredTypes = getTypeEnvFromDeclaredTypes();
if (scope.isFunction() && scope.hasUndeclaredFormalsOrOuters()) {
Collections.reverse(workset);
// Ideally, we would like to only set the in-edges of the implicit return
// rather than all edges. However, we cannot do that because of a bug in
// workset construction. (The test testBadWorksetConstruction would fail.)
// In buildWorksetHelper, if a loop contains break, we add the FOLLOW node
// of the loop before adding the loop header twice. So, the 2nd addition
// of the loop header has no effect. We should fix workset creation
// (eg, by putting edges instead of nodes in seen, or some other way that
// correctly waits for all incoming edges).
for (DiGraphEdge<Node, ControlFlowGraph.Branch> e : this.cfg.getEdges()) {
envs.put(e, this.typeEnvFromDeclaredTypes);
}
analyzeFunctionBwd(workset);
Collections.reverse(workset);
// TODO(dimvar): Revisit what we throw away after the bwd analysis
TypeEnv entryEnv = getEntryTypeEnv();
initEdgeEnvsFwd(entryEnv);
if (measureMem) {
updatePeakMem();
}
} else {
TypeEnv entryEnv = this.typeEnvFromDeclaredTypes;
initEdgeEnvsFwd(entryEnv);
}
this.typeEnvFromDeclaredTypes = null;
analyzeFunctionFwd(workset);
if (scope.isFunction()) {
createSummary(scope);
}
if (measureMem) {
updatePeakMem();
}
}
private void analyzeFunctionBwd(
List<DiGraphNode<Node, ControlFlowGraph.Branch>> workset) {
for (DiGraphNode<Node, ControlFlowGraph.Branch> dn : workset) {
Node n = dn.getValue();
TypeEnv outEnv = Preconditions.checkNotNull(getOutEnv(dn));
TypeEnv inEnv;
println("\tBWD Statment: ", n);
println("\t\toutEnv: ", outEnv);
switch (n.getToken()) {
case EXPR_RESULT:
inEnv = analyzeExprBwd(n.getFirstChild(), outEnv, UNKNOWN).env;
break;
case RETURN: {
Node retExp = n.getFirstChild();
if (retExp == null) {
inEnv = outEnv;
} else {
JSType declRetType = currentScope.getDeclaredFunctionType().getReturnType();
declRetType = declRetType == null ? UNKNOWN : declRetType;
inEnv = analyzeExprBwd(retExp, outEnv, declRetType).env;
}
break;
}
case VAR: {
if (NodeUtil.isTypedefDecl(n)) {
inEnv = outEnv;
break;
}
inEnv = outEnv;
for (Node nameNode = n.getFirstChild(); nameNode != null;
nameNode = nameNode.getNext()) {
String varName = nameNode.getString();
Node rhs = nameNode.getFirstChild();
JSType declType = currentScope.getDeclaredTypeOf(varName);
inEnv = envPutType(inEnv, varName, UNKNOWN);
if (rhs == null || currentScope.isLocalFunDef(varName)) {
continue;
}
JSType inferredType = envGetType(outEnv, varName);
JSType requiredType;
if (declType == null) {
requiredType = inferredType;
} else {
// TODO(dimvar): look if the meet is needed
requiredType = JSType.meet(declType, inferredType);
if (requiredType.isBottom()) {
requiredType = UNKNOWN;
}
}
inEnv = analyzeExprBwd(rhs, inEnv, requiredType).env;
}
break;
}
case BLOCK:
case ROOT:
case BREAK:
case CATCH:
case CONTINUE:
case DEFAULT_CASE:
case DEBUGGER:
case EMPTY:
case SCRIPT:
case TRY:
case WITH:
inEnv = outEnv;
break;
case DO:
case FOR:
case FOR_IN:
case IF:
case WHILE:
Node expr = n.isForIn() ? n.getFirstChild() : NodeUtil.getConditionExpression(n);
inEnv = analyzeExprBwd(expr, outEnv).env;
break;
case THROW:
case CASE:
case SWITCH:
inEnv = analyzeExprBwd(n.getFirstChild(), outEnv).env;
break;
default:
if (NodeUtil.isStatement(n)) {
throw new RuntimeException("Unhandled statement type: " + n.getToken());
} else {
inEnv = analyzeExprBwd(n, outEnv).env;
break;
}
}
println("\t\tinEnv: ", inEnv);
for (DiGraphEdge<Node, ControlFlowGraph.Branch> de : dn.getInEdges()) {
envs.put(de, inEnv);
}
}
}
private void analyzeFunctionFwd(
List<DiGraphNode<Node, ControlFlowGraph.Branch>> workset) {
for (DiGraphNode<Node, ControlFlowGraph.Branch> dn : workset) {
Node n = dn.getValue();
Node parent = n.getParent();
Preconditions.checkState(n != null,
"Implicit return should not be in workset.");
TypeEnv inEnv = getInEnv(dn);
TypeEnv outEnv = null;
if (parent.isScript()
|| (parent.isBlock() && parent.getParent().isFunction())) {
// All joins have merged; forget changes
inEnv = inEnv.clearChangeLog();
}
println("\tFWD Statment: ", n);
println("\t\tinEnv: ", inEnv);
boolean conditional = false;
switch (n.getToken()) {
case BLOCK:
case ROOT:
case BREAK:
case CONTINUE:
case DEFAULT_CASE:
case DEBUGGER:
case EMPTY:
case FUNCTION:
case SCRIPT:
case TRY:
case WITH: // We don't typecheck WITH, we just avoid crashing.
outEnv = inEnv;
break;
case CATCH:
String catchVarname = n.getFirstChild().getString();
outEnv = envPutType(inEnv, catchVarname, UNKNOWN);
break;
case EXPR_RESULT:
println("\tsemi ", n.getFirstChild().getToken());
if (n.getBooleanProp(Node.ANALYZED_DURING_GTI)) {
n.removeProp(Node.ANALYZED_DURING_GTI);
outEnv = inEnv;
} else {
outEnv = analyzeExprFwd(n.getFirstChild(), inEnv, UNKNOWN).env;
}
break;
case RETURN: {
Node retExp = n.getFirstChild();
JSType declRetType = currentScope.getDeclaredFunctionType().getReturnType();
if (declRetType == null) {
declRetType = UNKNOWN;
} else if (this.areTypeVariablesUnknown) {
declRetType = declRetType.substituteGenericsWithUnknown();
}
JSType actualRetType;
if (retExp == null) {
actualRetType = UNDEFINED;
outEnv = envPutType(inEnv, RETVAL_ID, actualRetType);
} else {
EnvTypePair retPair = analyzeExprFwd(retExp, inEnv, declRetType);
actualRetType = retPair.type;