-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
JSType.java
2522 lines (2265 loc) · 82.8 KB
/
JSType.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.newtypes;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import com.google.javascript.jscomp.NodeUtil;
import com.google.javascript.jscomp.parsing.parser.util.format.SimpleFormat;
import com.google.javascript.rhino.FunctionTypeI;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.ObjectTypeI;
import com.google.javascript.rhino.TypeI;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
/**
*
* @author blickly@google.com (Ben Lickly)
* @author dimvar@google.com (Dimitris Vardoulakis)
*/
public abstract class JSType implements TypeI, FunctionTypeI, ObjectTypeI {
private static final int BOTTOM_MASK = 0x0;
private static final int TYPEVAR_MASK = 0x1;
private static final int NON_SCALAR_MASK = 0x2;
private static final int ENUM_MASK = 0x4;
// The less important use case for TRUE_MASK and FALSE_MASK is to type the
// values true and false precisely. But people don't write: if (true) {...}
// More importantly, these masks come up as the negation of TRUTHY_MASK and
// FALSY_MASK when the ! operator is used.
private static final int TRUE_MASK = 0x8; // These two print out
private static final int FALSE_MASK = 0x10; // as 'boolean'
private static final int NULL_MASK = 0x20;
private static final int NUMBER_MASK = 0x40;
private static final int STRING_MASK = 0x80;
private static final int UNDEFINED_MASK = 0x100;
private static final int END_MASK = UNDEFINED_MASK * 2;
// When either of the next two bits is set, the rest of the type isn't
// guaranteed to be in a consistent state.
private static final int TRUTHY_MASK = 0x200;
private static final int FALSY_MASK = 0x400;
// Room to grow.
private static final int UNKNOWN_MASK = 0x7fffffff; // @type {?}
private static final int TOP_MASK = 0xffffffff; // @type {*}
private static final int BOOLEAN_MASK = TRUE_MASK | FALSE_MASK;
private static final int TOP_SCALAR_MASK =
NUMBER_MASK | STRING_MASK | BOOLEAN_MASK | NULL_MASK | UNDEFINED_MASK;
//Masks for common types:
private static final int NUMBER_OR_STRING_MASK = NUMBER_MASK | STRING_MASK;
// union of undefined and stuff
private static final int UNDEFINED_OR_BOOLEAN_MASK = UNDEFINED_MASK | TRUE_MASK | FALSE_MASK;
private static final int UNDEFINED_OR_NUMBER_MASK = UNDEFINED_MASK | NUMBER_MASK;
private static final int UNDEFINED_OR_STRING_MASK = UNDEFINED_MASK | STRING_MASK;
private static final int UNDEFINED_OR_NULL_MASK = UNDEFINED_MASK | NULL_MASK;
// union of null and stuff
private static final int NULL_OR_BOOLEAN_MASK = NULL_MASK | TRUE_MASK | FALSE_MASK;
private static final int NULL_OR_NUMBER_MASK = NULL_MASK | NUMBER_MASK;
private static final int NULL_OR_STRING_MASK = NULL_MASK | STRING_MASK;
private static final ImmutableSet<ObjectType> NO_OBJS = ImmutableSet.<ObjectType>of();
private static final ImmutableSet<EnumType> NO_ENUMS = ImmutableSet.<EnumType>of();
private final JSTypes commonTypes;
// Used only for development, to test performance of the code without the cost
// of printing the error messages.
public static boolean mockToString = false;
private JSType(JSTypes commonTypes) {
checkNotNull(commonTypes);
this.commonTypes = commonTypes;
}
private static JSType makeType(JSTypes commonTypes,
int mask, ImmutableSet<ObjectType> objs,
String typeVar, ImmutableSet<EnumType> enums) {
// Fix up the mask for objects and enums
if (checkNotNull(enums).isEmpty()) {
mask &= ~ENUM_MASK;
} else {
mask |= ENUM_MASK;
}
if (checkNotNull(objs).isEmpty()) {
mask &= ~NON_SCALAR_MASK;
} else {
mask |= NON_SCALAR_MASK;
}
if (objs.isEmpty() && enums.isEmpty()
&& typeVar == null && (mask & TYPEVAR_MASK) == 0) {
return makeMaskType(commonTypes, mask);
}
if (!JSType.isInhabitable(objs)) {
return commonTypes.BOTTOM;
}
if (mask == NON_SCALAR_MASK) {
return new ObjsType(commonTypes, objs);
}
if (mask == (NON_SCALAR_MASK | NULL_MASK)) {
return new NullableObjsType(commonTypes, objs);
}
return new UnionType(commonTypes, mask, objs, typeVar, enums);
}
private static JSType makeType(JSTypes commonTypes, int mask) {
return makeType(commonTypes, mask, NO_OBJS, null, NO_ENUMS);
}
static JSType makeMaskType(JSTypes commonTypes, int mask) {
switch (mask) {
case BOTTOM_MASK:
return commonTypes.BOTTOM;
case TRUE_MASK:
return commonTypes.TRUE_TYPE;
case FALSE_MASK:
return commonTypes.FALSE_TYPE;
case NULL_MASK:
return commonTypes.NULL;
case NUMBER_MASK:
return commonTypes.NUMBER;
case STRING_MASK:
return commonTypes.STRING;
case UNDEFINED_MASK:
return commonTypes.UNDEFINED;
case TRUTHY_MASK:
return commonTypes.TRUTHY;
case FALSY_MASK:
return commonTypes.FALSY;
case UNKNOWN_MASK:
return commonTypes.UNKNOWN;
case TOP_MASK:
return commonTypes.TOP;
case BOOLEAN_MASK:
return commonTypes.BOOLEAN;
case NUMBER_OR_STRING_MASK:
return commonTypes.NUMBER_OR_STRING;
case UNDEFINED_OR_BOOLEAN_MASK:
return commonTypes.UNDEFINED_OR_BOOLEAN;
case UNDEFINED_OR_NUMBER_MASK:
return commonTypes.UNDEFINED_OR_NUMBER;
case UNDEFINED_OR_STRING_MASK:
return commonTypes.UNDEFINED_OR_STRING;
case UNDEFINED_OR_NULL_MASK:
return commonTypes.NULL_OR_UNDEFINED;
case NULL_OR_BOOLEAN_MASK:
return commonTypes.NULL_OR_BOOLEAN;
case NULL_OR_NUMBER_MASK:
return commonTypes.NULL_OR_NUMBER;
case NULL_OR_STRING_MASK:
return commonTypes.NULL_OR_STRING;
default:
return new MaskType(commonTypes, mask);
}
}
protected abstract int getMask();
abstract ImmutableSet<ObjectType> getObjs();
protected abstract String getTypeVar();
protected abstract ImmutableSet<EnumType> getEnums();
// Factory method for wrapping a function in a JSType
static JSType fromFunctionType(FunctionType fn, NominalType fnNominal) {
return makeType(
fn.getCommonTypes(),
NON_SCALAR_MASK,
ImmutableSet.of(ObjectType.fromFunction(fn, fnNominal)),
null, NO_ENUMS);
}
public static JSType fromObjectType(ObjectType obj) {
return makeType(obj.getCommonTypes(), NON_SCALAR_MASK, ImmutableSet.of(obj), null, NO_ENUMS);
}
public static JSType fromTypeVar(JSTypes commonTypes, String typevarName) {
return makeType(commonTypes, TYPEVAR_MASK, NO_OBJS, typevarName, NO_ENUMS);
}
static JSType fromEnum(EnumType e) {
return makeType(e.getCommonTypes(), ENUM_MASK, NO_OBJS, null, ImmutableSet.of(e));
}
final boolean isValidType() {
if (isUnknown() || isTop()) {
return true;
}
if ((getMask() & NON_SCALAR_MASK) != 0
&& getObjs().isEmpty()) {
return false;
}
if ((getMask() & NON_SCALAR_MASK) == 0 && !getObjs().isEmpty()) {
return false;
}
if ((getMask() & ENUM_MASK) != 0
&& getEnums().isEmpty()) {
return false;
}
if ((getMask() & ENUM_MASK) == 0 && !getEnums().isEmpty()) {
return false;
}
return ((getMask() & TYPEVAR_MASK) != 0) == (getTypeVar() != null);
}
static Map<String, JSType> createScalars(JSTypes commonTypes) {
LinkedHashMap<String, JSType> types = new LinkedHashMap<>();
types.put("BOOLEAN", new MaskType(commonTypes, TRUE_MASK | FALSE_MASK));
types.put("BOTTOM", new MaskType(commonTypes, BOTTOM_MASK));
types.put("FALSE_TYPE", new MaskType(commonTypes, FALSE_MASK));
types.put("FALSY", new MaskType(commonTypes, FALSY_MASK));
types.put("NULL", new MaskType(commonTypes, NULL_MASK));
types.put("NUMBER", new MaskType(commonTypes, NUMBER_MASK));
types.put("STRING", new MaskType(commonTypes, STRING_MASK));
types.put("TOP", new MaskType(commonTypes, TOP_MASK));
types.put("TOP_SCALAR", new MaskType(commonTypes, TOP_SCALAR_MASK));
types.put("TRUE_TYPE", new MaskType(commonTypes, TRUE_MASK));
types.put("TRUTHY", new MaskType(commonTypes, TRUTHY_MASK));
types.put("UNDEFINED", new MaskType(commonTypes, UNDEFINED_MASK));
types.put("UNKNOWN", new MaskType(commonTypes, UNKNOWN_MASK));
types.put("UNDEFINED_OR_BOOLEAN", new MaskType(commonTypes, UNDEFINED_OR_BOOLEAN_MASK));
types.put("UNDEFINED_OR_NUMBER", new MaskType(commonTypes, UNDEFINED_OR_NUMBER_MASK));
types.put("UNDEFINED_OR_STRING", new MaskType(commonTypes, UNDEFINED_OR_STRING_MASK));
types.put("NULL_OR_BOOLEAN", new MaskType(commonTypes, NULL_OR_BOOLEAN_MASK));
types.put("NULL_OR_NUMBER", new MaskType(commonTypes, NULL_OR_NUMBER_MASK));
types.put("NULL_OR_STRING", new MaskType(commonTypes, NULL_OR_STRING_MASK));
types.put("NULL_OR_UNDEFINED", new MaskType(commonTypes, NULL_MASK | UNDEFINED_MASK));
types.put("NUMBER_OR_STRING", new MaskType(commonTypes, NUMBER_MASK | STRING_MASK));
return types;
}
@Override
public final boolean isTop() {
return TOP_MASK == getMask();
}
@Override
public final boolean isBottom() {
return BOTTOM_MASK == getMask();
}
public final boolean isUndefined() {
return UNDEFINED_MASK == getMask();
}
public final boolean isUnknown() {
return UNKNOWN_MASK == getMask();
}
public final boolean isTrueOrTruthy() {
return TRUTHY_MASK == getMask() || TRUE_MASK == getMask();
}
private boolean isTheTruthyType() {
return TRUTHY_MASK == getMask();
}
private boolean isTheTrueType() {
return TRUE_MASK == getMask();
}
public final boolean isFalseOrFalsy() {
return FALSY_MASK == getMask() || FALSE_MASK == getMask();
}
// Ignoring enums for simplicity
public final boolean isAnyTruthyType() {
int mask = getMask();
int truthyMask = TRUTHY_MASK | TRUE_MASK | NON_SCALAR_MASK;
return mask != BOTTOM_MASK && (mask | truthyMask) == truthyMask;
}
// Ignoring enums for simplicity
public final boolean isAnyFalsyType() {
int mask = getMask();
int falsyMask = FALSY_MASK | FALSE_MASK | NULL_MASK | UNDEFINED_MASK;
return mask != BOTTOM_MASK && (mask | falsyMask) == falsyMask;
}
private boolean isTheFalsyType() {
return FALSY_MASK == getMask();
}
private boolean isTheFalseType() {
return FALSE_MASK == getMask();
}
public final boolean isBoolean() {
return (getMask() & ~BOOLEAN_MASK) == 0 && (getMask() & BOOLEAN_MASK) != 0;
}
@Override
public final boolean isBooleanValueType() {
return isBoolean();
}
public final boolean isString() {
return STRING_MASK == getMask();
}
@Override
public final boolean isStringValueType() {
return isString();
}
public final boolean isNumber() {
return NUMBER_MASK == getMask();
}
@Override
public final boolean isNumberValueType() {
return isNumber();
}
public final boolean isNullOrUndef() {
int nullUndefMask = NULL_MASK | UNDEFINED_MASK;
return getMask() != 0 && (getMask() | nullUndefMask) == nullUndefMask;
}
public final boolean isScalar() {
return getMask() == NUMBER_MASK
|| getMask() == STRING_MASK
|| getMask() == NULL_MASK
|| getMask() == UNDEFINED_MASK
|| isBoolean();
}
// True iff there exists a value that can have this type
private static boolean isInhabitable(Set<ObjectType> objs) {
for (ObjectType obj : objs) {
if (!obj.isInhabitable()) {
return false;
}
}
return true;
}
final JSTypes getCommonTypes() {
return this.commonTypes;
}
final boolean hasScalar() {
return (getMask() & TOP_SCALAR_MASK) != 0 || EnumType.hasScalar(getEnums());
}
public final boolean hasNonScalar() {
return !getObjs().isEmpty() || EnumType.hasNonScalar(getEnums());
}
@Override
public final boolean isNullable() {
return !isTop() && (getMask() & NULL_MASK) != 0;
}
@Override
public final boolean isTypeVariable() {
return getMask() == TYPEVAR_MASK;
}
public final boolean hasTypeVariable() {
return (getMask() & TYPEVAR_MASK) != 0;
}
public final boolean isStruct() {
if (isUnknown()) {
return false;
}
Preconditions.checkState(!getObjs().isEmpty(),
"Expected object type but found %s", this);
for (ObjectType objType : getObjs()) {
if (!objType.isStruct()) {
return false;
}
}
return true;
}
public final boolean mayBeStruct() {
for (ObjectType objType : getObjs()) {
if (objType.isStruct()) {
return true;
}
}
return false;
}
public final boolean isStructWithoutProp(QualifiedName pname) {
for (ObjectType obj : getObjs()) {
if (obj.isStruct() && !obj.mayHaveProp(pname)) {
return true;
}
}
return false;
}
public final boolean isLoose() {
ImmutableSet<ObjectType> objs = getObjs();
return objs.size() == 1 && Iterables.getOnlyElement(objs).isLoose();
}
public final boolean isDict() {
if (isUnknown()) {
return false;
}
checkState(!getObjs().isEmpty());
for (ObjectType objType : getObjs()) {
if (!objType.isDict()) {
return false;
}
}
return true;
}
// Returns null if this type doesn't inherit from IObject
public final JSType getIndexType() {
if (getMask() != NON_SCALAR_MASK) {
return null;
}
// This (union) type is a supertype of all indexed types in the union.
// Different from NominalType#getIndexType, which uses join.
JSType result = this.commonTypes.TOP;
// We need this because the index type may explicitly be TOP.
boolean foundIObject = false;
for (ObjectType objType : getObjs()) {
JSType tmp = objType.getNominalType().getIndexType();
if (tmp == null) {
return null;
}
foundIObject = true;
result = meet(result, tmp);
}
return foundIObject ? result : null;
}
// May be called for types that include non-objects, and we ignore the
// non-object parts in those cases.
public final JSType getIndexedType() {
if ((getMask() & NON_SCALAR_MASK) == 0) {
return null;
}
JSType result = this.commonTypes.BOTTOM;
for (ObjectType objType : getObjs()) {
JSType tmp = objType.getNominalType().getIndexedType();
if (tmp == null) {
return null;
}
result = join(result, tmp);
}
return result.isBottom() ? null : result;
}
public final boolean mayBeDict() {
for (ObjectType objType : getObjs()) {
if (objType.isDict()) {
return true;
}
}
return false;
}
@Override
public final boolean isEnumElement() {
return getMask() == ENUM_MASK && getEnums().size() == 1;
}
@Override
public final boolean isEnumObject() {
ObjectType obj = getObjTypeIfSingletonObj();
return obj != null && obj.isEnumObject();
}
@Override
public final TypeI getEnumeratedTypeOfEnumObject() {
return isEnumObject() ? getObjTypeIfSingletonObj().getEnumType().getEnumeratedType() : null;
}
public final boolean isUnion() {
if (isBottom() || isTop() || isUnknown()
|| isScalar() || isTypeVariable() || isEnumElement()
|| isTheTruthyType() || isTheFalsyType()) {
return false;
}
return !(getMask() == NON_SCALAR_MASK && getObjs().size() == 1);
}
public final boolean isFunctionWithProperties() {
ObjectType obj = getObjTypeIfSingletonObj();
return obj != null && obj.isFunctionWithProperties();
}
public final boolean isNamespace() {
ObjectType obj = getObjTypeIfSingletonObj();
return obj != null && obj.isNamespace();
}
// Only makes sense for a JSType that represents a single enum
@Override
public final JSType getEnumeratedTypeOfEnumElement() {
return isEnumElement() ?
Iterables.getOnlyElement(getEnums()).getEnumeratedType() : null;
}
@Override
public final JSType autobox() {
if (isTop() || isUnknown()) {
return this;
}
int mask = getMask();
if ((mask & (NUMBER_MASK | STRING_MASK | BOOLEAN_MASK | ENUM_MASK)) == BOTTOM_MASK) {
return this;
}
switch (mask) {
case NUMBER_MASK:
return this.commonTypes.getNumberInstance();
case BOOLEAN_MASK:
case TRUE_MASK:
case FALSE_MASK:
return this.commonTypes.getBooleanInstance();
case STRING_MASK:
return this.commonTypes.getStringInstance();
default:
// Not a scalar type: handled below.
}
// For each set bit, add the corresponding obj to the new objs
// construct and return the new type.
// Don't bother autoboxing enums.
ImmutableSet.Builder<ObjectType> builder = ImmutableSet.builder();
builder.addAll(getObjs());
if ((mask & NUMBER_MASK) != 0) {
builder.add(this.commonTypes.getNumberInstanceObjType());
}
if ((mask & STRING_MASK) != 0) {
builder.add(this.commonTypes.getStringInstanceObjType());
}
if ((mask & BOOLEAN_MASK) != 0) { // may have truthy or falsy
builder.add(this.commonTypes.getBooleanInstanceObjType());
}
JSType result = makeType(
this.commonTypes,
mask & ~(NUMBER_MASK | STRING_MASK | BOOLEAN_MASK),
builder.build(), getTypeVar(), NO_ENUMS);
for (EnumType e : getEnums()) {
result = join(result, e.getEnumeratedType().autobox());
}
return result;
}
static JSType nullAcceptingJoin(JSType t1, JSType t2) {
if (t1 == null) {
return t2;
} else if (t2 == null) {
return t1;
}
return JSType.join(t1, t2);
}
static JSType joinManyTypes(JSTypes commonTypes, Iterable<JSType> types) {
JSType result = commonTypes.BOTTOM;
for (JSType t : types) {
result = join(result, t);
}
return result;
}
// When joining w/ TOP or UNKNOWN, avoid setting more fields on them, eg, obj.
public static JSType join(JSType lhs, JSType rhs) {
checkNotNull(lhs);
checkNotNull(rhs);
JSTypes commonTypes = lhs.commonTypes;
if (lhs.isTop() || rhs.isTop()) {
return commonTypes.TOP;
}
if (lhs.isUnknown() || rhs.isUnknown()) {
return commonTypes.UNKNOWN;
}
if (lhs.isBottom()) {
return rhs;
}
if (rhs.isBottom()) {
return lhs;
}
if (lhs.isTheTruthyType() || lhs.isTheFalsyType()
|| rhs.isTheTruthyType() || rhs.isTheFalsyType()) {
return commonTypes.UNKNOWN;
}
if (lhs.getTypeVar() != null && rhs.getTypeVar() != null
&& !lhs.getTypeVar().equals(rhs.getTypeVar())) {
// For now return ? when joining two type vars. This is probably uncommon.
return commonTypes.UNKNOWN;
}
int newMask = lhs.getMask() | rhs.getMask();
ImmutableSet<ObjectType> newObjs =
ObjectType.joinSets(lhs.getObjs(), rhs.getObjs());
String newTypevar =
lhs.getTypeVar() != null ? lhs.getTypeVar() : rhs.getTypeVar();
ImmutableSet<EnumType> newEnums =
EnumType.union(lhs.getEnums(), rhs.getEnums());
if (newEnums.isEmpty()) {
return makeType(commonTypes, newMask, newObjs, newTypevar, NO_ENUMS);
}
JSType tmpJoin =
makeType(commonTypes, newMask & ~ENUM_MASK, newObjs, newTypevar, NO_ENUMS);
return makeType(commonTypes, newMask, newObjs,
newTypevar, EnumType.normalizeForJoin(newEnums, tmpJoin));
}
/**
* Creates a new JSType by deeply substituting the *free* type variables in this type with
* concrete replacements from the given map.
* This is also what all other substituteGenerics methods in this package do.
*
* Do not confuse with the instantiateGenerics methods, which take an *uninstantiated*
* generic type (a nominal type or a generic function), and substitute the *bound* type variables
* with the concrete types from the map.
* For example, when you define a class Foo with T, an
* uninstantiated Foo object has type: {@code ForAll T.Foo<T>}.
* When you define a generic function f with U, that takes a {@code Foo<U>} as an argument and
* returns a U, f's type is {@code ForAll U.Foo<U> => U}.
* When you call f with some argument, say Foo of string, you instantiate U in f's type.
* The part of f's type without the ForAll contains U as a free type variable.
* So you call substituteGenerics in order to convert the {@code Foo<U>} to a {@code Foo<string>}
*/
public final JSType substituteGenerics(Map<String, JSType> concreteTypes) {
if (isTop()
|| isUnknown()
|| (getObjs().isEmpty() && getTypeVar() == null)
|| concreteTypes.isEmpty()) {
return this;
}
// TODO(dimvar): By adding prints, I found that the majority of the time, when
// we substitute generics in obj, it has no effect; the result is equal to the type
// before substitution. I did some timing tests to estimate what the improvement
// would be if we did better here, and they were inconclusive because of large variance
// in the test runs. Intuitively though, it seems that we can save time here,
// so revisit this in the future when I have time to dig in deeper.
ImmutableSet.Builder<ObjectType> builder = ImmutableSet.builder();
for (ObjectType obj : getObjs()) {
builder.add(obj.substituteGenerics(concreteTypes));
}
JSType current = makeType(
this.commonTypes, getMask() & ~TYPEVAR_MASK, builder.build(), null, getEnums());
if (hasTypeVariable()) {
current = JSType.join(current, concreteTypes.containsKey(getTypeVar()) ?
concreteTypes.get(getTypeVar()) : fromTypeVar(this.commonTypes, getTypeVar()));
}
return current;
}
public final JSType substituteGenericsWithUnknown() {
return substituteGenerics(this.commonTypes.MAP_TO_UNKNOWN);
}
/**
* Given an generic supertype of this,
* returns the type argument as instantiated by this type.
*
* Parameter supertype has to be a type with a single type parameter.
*
* For example,<pre> {@code
* (Iterable<Foo>).getInstantiatedTypeArgument(Iterable<?>) returns Foo,
* and
* /** {@literal @}template A * /
* class Foo {}
* /**
* * {@literal @}template B
* * {@literal @}extends {Foo<Array<B>>}
* * /
* class Bar {}
* (Bar<string>).getInstantiatedTypeArguments(Bar<?>) returns string
* (Bar<string>).getInstantiatedTypeArguments(Foo<?>) returns Array<string>
* }</pre>
* This is used, for example, in type-checking for-of and yield.
*/
public JSType getInstantiatedTypeArgument(JSType supertype) {
RawNominalType rawType =
supertype.getNominalTypeIfSingletonObj().getRawNominalType();
List<String> typeParameters = rawType.getTypeParameters();
checkState(typeParameters.size() == 1);
String param = typeParameters.get(0);
Map<String, JSType> typeMap = new LinkedHashMap<>();
typeMap.put(param, JSType.fromTypeVar(this.commonTypes, param));
JSType reinstantiated = rawType.getInstanceAsJSType().substituteGenerics(typeMap);
Multimap<String, JSType> typeMultimap = LinkedHashMultimap.create();
reinstantiated.unifyWith(this, typeParameters, typeMultimap);
return joinManyTypes(this.commonTypes, typeMultimap.get(param));
}
private static void updateTypemap(
Multimap<String, JSType> typeMultimap,
String typeParam, JSType type) {
checkNotNull(type);
Set<JSType> typesToRemove = new LinkedHashSet<>();
for (JSType other : typeMultimap.get(typeParam)) {
if (type.isUnknown()) {
typesToRemove.add(other);
continue;
}
if (other.isUnknown()) {
type = null;
break;
}
// The only way to instantiate with a loose type is if there are no
// concrete types available. We may miss some warnings this way but we
// also avoid false positives.
if (type.isLoose()) {
type = null;
break;
} else if (other.isLoose()) {
typesToRemove.add(other);
continue;
}
JSType unified = unifyUnknowns(type, other);
if (unified != null) {
// Can't remove elms while iterating over the collection, so do it later
typesToRemove.add(other);
type = unified;
} else if (other.isSubtypeOf(type, SubtypeCache.create())) {
typesToRemove.add(other);
} else if (type.isSubtypeOf(other, SubtypeCache.create())) {
type = null;
break;
}
}
for (JSType typeToRemove : typesToRemove) {
typeMultimap.remove(typeParam, typeToRemove);
}
if (type != null) {
typeMultimap.put(typeParam, type);
}
}
private final JSType promoteBoolean() {
return isTheTrueType() || isTheFalseType() ? this.commonTypes.BOOLEAN : this;
}
private static int promoteBooleanMask(int mask) {
if ((mask & (TRUE_MASK | FALSE_MASK)) != 0) {
return mask | TRUE_MASK | FALSE_MASK;
}
return mask;
}
/**
* Unify the two types symmetrically, given that we have already instantiated
* the type variables of interest in {@code t1} and {@code t2}, treating
* JSType.UNKNOWN as a "hole" to be filled.
* @return The unified type, or null if unification fails */
static JSType unifyUnknowns(JSType t1, JSType t2) {
checkNotNull(t1);
checkNotNull(t2);
if (t1.isUnknown() || t1.isLoose()) {
return t2;
} else if (t2.isUnknown() || t2.isLoose()) {
return t1;
} else if (t1.isTop() && t2.isTop()) {
return t1.commonTypes.TOP;
} else if (t1.isTop() || t2.isTop()) {
return null;
}
if (!t1.getEnums().equals(t2.getEnums())) {
return null;
}
ImmutableSet<EnumType> newEnums = t1.getEnums();
int t1Mask = promoteBooleanMask(t1.getMask());
int t2Mask = promoteBooleanMask(t2.getMask());
if (t1Mask != t2Mask || !Objects.equals(t1.getTypeVar(), t2.getTypeVar())) {
return null;
}
// All scalar types are equal
if ((t1Mask & NON_SCALAR_MASK) == 0) {
return t1;
}
if (t1.getObjs().size() != t2.getObjs().size()) {
return null;
}
Set<ObjectType> ununified = new LinkedHashSet<>(t2.getObjs());
Set<ObjectType> unifiedObjs = new LinkedHashSet<>();
for (ObjectType objType1 : t1.getObjs()) {
ObjectType unified = objType1;
boolean hasUnified = false;
for (ObjectType objType2 : t2.getObjs()) {
ObjectType tmp = ObjectType.unifyUnknowns(unified, objType2);
if (tmp != null) {
hasUnified = true;
ununified.remove(objType2);
unified = tmp;
}
}
if (!hasUnified) {
return null;
}
unifiedObjs.add(unified);
}
if (!ununified.isEmpty()) {
return null;
}
return makeType(t1.commonTypes, t1Mask,
ImmutableSet.copyOf(unifiedObjs), t1.getTypeVar(), newEnums);
}
/**
* Unify {@code this}, which may contain free type variables,
* with {@code other}, a concrete subtype, modifying the supplied
* {@code typeMultimap} to add any new template variable type bindings.
*
* This method should only be called outside the newtypes package;
* classes inside the package should use unifyWithSubtype.
*
* Unification algorithm.
*
* Say that {@code this} is a potentially generic type G and {@code other} is a concrete type C.
* 1. If C is not a union:
* (A) If C is a subtype of G, then unification succeeds and we don't update the type map.
* E.g., (T|string) unifies with string and we learn nothing about T.
* (B) If some member of G unifies with C, unification succeeds and we update the type map.
* (C) If 2+ members of G unify with C, we use each of them to update the type map. This is
* simpler than depending on the iteration order of the members of G to decide which one
* to unify with C.
* E.g., if Foo extends Bar and implements Baz,
* (Bar(T)|Baz(T)) unifies with Foo(number) and T is number.
* (Bar(number, T)|Baz(T, string)) doesn't unify with Foo(number,string), but each member
* unifies with C, and we get a "not unique instantiation" warning.
*
* 2. If C is a union:
* We throw away C's members that are subtypes of G, and for each remaining
* member we try to individually unify G with it. A single member of G may unify with
* 2+ members of C.
* Let SubC be a type that contains all members of C that are left over: they are not subtypes
* of G and G doesn't unify with them. If G is of the form (T|...), then T is mapped to SubC.
* E.g., (T|Foo|Bar(U)) unifies with (number|string|Foo|Bar(Baz))
* SubC is (number|string), T is mapped to (number|string), and U is mapped to Baz.
*/
public final void unifyWith(JSType other, List<String> typeParameters,
Multimap<String, JSType> typeMultimap) {
unifyWithSubtype(other, typeParameters, typeMultimap, SubtypeCache.create());
}
/**
* Unify this, which is a potentially generic type G, with other, a concrete type C.
* Unifying means finding concrete types to substitute for the type variables in G and get a
* type G', such that C is a subtype of G'.
*
* Doing unification of function types correctly also requires a unifyWithSupertype method.
* See {@link FunctionType#unifyWithSubtype} for details. For now, we think that's an overkill.
*
* @param subSuperMap needed to avoid infinite recursion when unifying structural interfaces.
* @return whether unification succeeded
*/
final boolean unifyWithSubtype(JSType other, List<String> typeParameters,
Multimap<String, JSType> typeMultimap, SubtypeCache subSuperMap) {
if (other.isUnknown()) {
String thisTypevar = getTypeVar();
if (thisTypevar != null && typeParameters.contains(thisTypevar)) {
updateTypemap(typeMultimap, thisTypevar, other);
}
return true;
}
HashSet<JSType> leftovers = new HashSet<>();
for (JSType otherMember : other.getUnionMembers()) {
if (otherMember.isSubtypeOf(this)) {
continue;
}
otherMember = otherMember.promoteBoolean();
if (!unifyWithSingleType(otherMember, typeParameters, typeMultimap, subSuperMap)) {
leftovers.add(otherMember);
}
}
if (leftovers.isEmpty()) {
return true;
}
String thisTypevar = getTypeVar();
if (thisTypevar != null && typeParameters.contains(thisTypevar)) {
updateTypemap(typeMultimap, thisTypevar, joinManyTypes(this.commonTypes, leftovers));
return true;
}
return false;
}
/**
* Unify other, which is NOT a union type, with this, which may be a union.
* Note that if other is a primitive type then this method will always return false:
* primitives may only be unified with a typevar as "leftovers".
*/
final boolean unifyWithSingleType(JSType other, List<String> typeParameters,
Multimap<String, JSType> typeMultimap, SubtypeCache subSuperMap) {
Preconditions.checkArgument(!other.isUnion(), "Expected non-union type but found: %s", other);
if (other.isEnumElement()) {
JSType enumType = other.getEnumeratedTypeOfEnumElement();
return unifyWithSingleType(enumType, typeParameters, typeMultimap, subSuperMap);
}
if (other.isSingletonObj()) {
ObjectType otherObj = other.getObjTypeIfSingletonObj();
boolean result = false;
for (ObjectType thisObj : getObjs()) {
// Note that we want to execute thisObj.unifyWithSubtype(otherObj, ...) even if result
// is already true, because several members of the generic type may unify with otherObj.
if (thisObj.unifyWithSubtype(otherObj, typeParameters, typeMultimap, subSuperMap)) {
result = true;
}
}
return result;
}
return false;
}
public final JSType specialize(JSType other) {
JSType t = specializeHelper(other);
if (t.isBottom() && (isLoose() || other.isLoose())) {
t = autobox().specializeHelper(other.autobox());
// If the autoboxed specialization is not null, this means that one of
// the two types contains scalars that when autoboxed are compatible with
// the loose object in the other type. In this case, don't return bottom,
// just leave the type unspecialized.
if (!t.isBottom()) {
return this;
}
}
return t.isLoose() ? ObjectType.mayTurnLooseObjectToScalar(t, this.commonTypes) : t;
}
@SuppressWarnings("ReferenceEquality")
private JSType specializeHelper(JSType other) {
if (other.isTop() || other.isUnknown() || this == other) {
return this;
}
if (other.isTheTruthyType()) {
return makeTruthy();
}
if (isTheTruthyType()) {
// If the only thing we know about this type is that it's truthy, that's very
// little information, so we loosen the other type to avoid spurious warnings.
JSType otherTruthy = other.makeTruthy();
return otherTruthy.hasNonScalar()
? otherTruthy.withLoose()
: otherTruthy;
}
if (other.isTheFalsyType()) {
return makeFalsy();
}
if (isTheFalsyType()) {
return other.makeFalsy();
}
if (this.isTop()) {
return other;
}
if (this.isUnknown()) {
NominalType otherNt = other.getNominalTypeIfSingletonObj();
return otherNt != null && otherNt.isBuiltinObject() ? other.withLoose() : other;
}
int newMask = getMask() & other.getMask();
String newTypevar;