/
JSType.java
1350 lines (1202 loc) · 41.2 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 com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import com.google.javascript.rhino.FunctionTypeI;
import com.google.javascript.rhino.ObjectTypeI;
import com.google.javascript.rhino.TypeI;
import java.util.Collection;
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 {
protected static final int BOTTOM_MASK = 0x0;
protected static final int TYPEVAR_MASK = 0x1;
protected static final int NON_SCALAR_MASK = 0x2;
protected static final int ENUM_MASK = 0x4;
protected static final int TRUE_MASK = 0x8; // These two print out
protected static final int FALSE_MASK = 0x10; // as 'boolean'
protected static final int NULL_MASK = 0x20;
protected static final int NUMBER_MASK = 0x40;
protected static final int STRING_MASK = 0x80;
protected static final int UNDEFINED_MASK = 0x100;
protected 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.
protected static final int TRUTHY_MASK = 0x200;
protected static final int FALSY_MASK = 0x400;
// Room to grow.
protected static final int UNKNOWN_MASK = 0x7fffffff; // @type {?}
protected static final int TOP_MASK = 0xffffffff; // @type {*}
protected static final int BOOLEAN_MASK = TRUE_MASK | FALSE_MASK;
protected static final int TOP_SCALAR_MASK =
NUMBER_MASK | STRING_MASK | BOOLEAN_MASK | NULL_MASK | UNDEFINED_MASK;
static final Map<String, JSType> MAP_TO_UNKNOWN =
new Map<String, JSType>() {
public void clear() {
throw new UnsupportedOperationException();
}
public boolean containsKey(Object k) {
return true;
}
public boolean containsValue(Object v) {
return v == JSType.UNKNOWN;
}
public Set<Map.Entry<String, JSType>> entrySet() {
throw new UnsupportedOperationException();
}
public JSType get(Object k) {
return JSType.UNKNOWN;
}
public boolean isEmpty() {
return false;
}
public Set<String> keySet() {
throw new UnsupportedOperationException();
}
public JSType put(String k, JSType v) {
throw new UnsupportedOperationException();
}
public void putAll(Map<? extends String, ? extends JSType> m) {
throw new UnsupportedOperationException();
}
public JSType remove(Object k) {
throw new UnsupportedOperationException();
}
public int size() {
throw new UnsupportedOperationException();
}
public Collection<JSType> values() {
return ImmutableSet.of(JSType.UNKNOWN);
}
public int hashCode() {
throw new UnsupportedOperationException();
}
public boolean equals(Object o) {
return o == this;
}
};
// Used only for development, to test performance of the code without the cost
// of printing the error messages.
public static boolean mockToString = false;
private static JSType makeType(int mask,
ImmutableSet<ObjectType> objs, String typeVar,
ImmutableSet<EnumType> enums) {
// Fix up the mask for objects and enums
if (Preconditions.checkNotNull(enums).isEmpty()) {
mask &= ~ENUM_MASK;
} else {
mask |= ENUM_MASK;
}
if (Preconditions.checkNotNull(objs).isEmpty()) {
mask &= ~NON_SCALAR_MASK;
} else {
mask |= NON_SCALAR_MASK;
}
if (objs.isEmpty() && typeVar == null && enums.isEmpty()) {
return MaskType.make(mask);
}
if (!JSType.isInhabitable(objs)) {
return BOTTOM;
}
if (mask == NON_SCALAR_MASK) {
return new ObjsType(objs);
}
if (mask == (NON_SCALAR_MASK | NULL_MASK)) {
return new NullableObjsType(objs);
}
return new UnionType(mask, objs, typeVar, enums);
}
private static JSType makeType(int mask) {
return makeType(mask, ImmutableSet.<ObjectType>of(), null, ImmutableSet.<EnumType>of());
}
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(
NON_SCALAR_MASK,
ImmutableSet.of(ObjectType.fromFunction(fn, fnNominal)),
null,
ImmutableSet.<EnumType>of());
}
public static JSType fromObjectType(ObjectType obj) {
return makeType(NON_SCALAR_MASK, ImmutableSet.of(obj), null, ImmutableSet.<EnumType>of());
}
public static JSType fromTypeVar(String template) {
return makeType(
TYPEVAR_MASK,
ImmutableSet.<ObjectType>of(),
template,
ImmutableSet.<EnumType>of());
}
static JSType fromEnum(EnumType e) {
return makeType(ENUM_MASK, ImmutableSet.<ObjectType>of(), null, ImmutableSet.of(e));
}
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);
}
public static final JSType BOOLEAN = new MaskType(TRUE_MASK | FALSE_MASK);
public static final JSType BOTTOM = new MaskType(BOTTOM_MASK);
public static final JSType FALSE_TYPE = new MaskType(FALSE_MASK);
public static final JSType FALSY = new MaskType(FALSY_MASK);
public static final JSType NULL = new MaskType(NULL_MASK);
public static final JSType NUMBER = new MaskType(NUMBER_MASK);
public static final JSType STRING = new MaskType(STRING_MASK);
public static final JSType TOP = new MaskType(TOP_MASK);
public static final JSType TOP_SCALAR = makeType(TOP_SCALAR_MASK);
public static final JSType TRUE_TYPE = new MaskType(TRUE_MASK);
public static final JSType TRUTHY = new MaskType(TRUTHY_MASK);
public static final JSType UNDEFINED = new MaskType(UNDEFINED_MASK);
public static final JSType UNKNOWN = new MaskType(UNKNOWN_MASK);
public static final JSType TOP_OBJECT = fromObjectType(ObjectType.TOP_OBJECT);
public static final JSType TOP_STRUCT = fromObjectType(ObjectType.TOP_STRUCT);
public static final JSType TOP_DICT = fromObjectType(ObjectType.TOP_DICT);
// Some commonly used types
public static final JSType NULL_OR_UNDEF =
new MaskType(NULL_MASK | UNDEFINED_MASK);
public static final JSType NUM_OR_STR =
new MaskType(NUMBER_MASK | STRING_MASK);
// Explicitly contains most types. Used only by removeType.
private static final JSType ALMOST_TOP = makeType(
TRUE_MASK | FALSE_MASK | NUMBER_MASK | STRING_MASK | NULL_MASK |
UNDEFINED_MASK | NON_SCALAR_MASK,
ImmutableSet.of(ObjectType.TOP_OBJECT), null, ImmutableSet.<EnumType>of());
public boolean isTop() {
return TOP_MASK == getMask();
}
@Override
public boolean isBottom() {
return BOTTOM_MASK == getMask();
}
public boolean isUnknown() {
return UNKNOWN_MASK == getMask();
}
public boolean isTruthy() {
return TRUTHY_MASK == getMask() || TRUE_MASK == getMask();
}
public boolean isFalsy() {
return FALSY_MASK == getMask() || FALSE_MASK == getMask();
}
public boolean isBoolean() {
return (getMask() & ~BOOLEAN_MASK) == 0 && (getMask() & BOOLEAN_MASK) != 0;
}
public boolean isString() {
return STRING_MASK == getMask();
}
public boolean isNumber() {
return NUMBER_MASK == getMask();
}
public boolean isNullOrUndef() {
int nullUndefMask = NULL_MASK | UNDEFINED_MASK;
return getMask() != 0 && (getMask() | nullUndefMask) == nullUndefMask;
}
public 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;
}
public boolean hasNonScalar() {
return !getObjs().isEmpty() || EnumType.hasNonScalar(getEnums());
}
public boolean isNullable() {
return (getMask() & NULL_MASK) != 0;
}
boolean isTypeVariable() {
return (getMask() & TYPEVAR_MASK) != 0 && (getMask() & ~TYPEVAR_MASK) == 0;
}
public boolean isStruct() {
for (ObjectType objType : getObjs()) {
if (objType.isStruct()) {
return true;
}
}
return false;
}
public boolean isLooseStruct() {
boolean foundLooseStruct = false;
boolean foundNonLooseStruct = false;
for (ObjectType objType : getObjs()) {
if (objType.isLooseStruct()) {
foundLooseStruct = true;
} else if (objType.isStruct()) {
foundNonLooseStruct = true;
}
}
return foundLooseStruct && !foundNonLooseStruct;
}
public boolean isLoose() {
ImmutableSet<ObjectType> objs = getObjs();
return objs.size() == 1 && Iterables.getOnlyElement(objs).isLoose();
}
public boolean isDict() {
for (ObjectType objType : getObjs()) {
if (objType.isDict()) {
return true;
}
}
return false;
}
public boolean isEnumElement() {
return getMask() == ENUM_MASK && getEnums().size() == 1;
}
public boolean isUnion() {
if (isBottom() || isTop() || isUnknown()
|| isScalar() || isTypeVariable() || isEnumElement()) {
return false;
}
return !(getMask() == NON_SCALAR_MASK && getObjs().size() == 1);
}
public static boolean areCompatibleScalarTypes(JSType lhs, JSType rhs) {
Preconditions.checkArgument(
lhs.isSubtypeOf(TOP_SCALAR) || rhs.isSubtypeOf(TOP_SCALAR));
return lhs.isBottom() || rhs.isBottom()
|| lhs.isUnknown() || rhs.isUnknown()
|| (lhs.isBoolean() && rhs.isBoolean()) || lhs.equals(rhs);
}
// Only makes sense for a JSType that represents a single enum
public JSType getEnumeratedType() {
return isEnumElement() ?
Iterables.getOnlyElement(getEnums()).getEnumeratedType() : null;
}
public JSType autobox(JSTypes commonTypes) {
if (isTop() || isUnknown()) {
return this;
}
int mask = getMask();
if ((mask & (NUMBER_MASK | STRING_MASK | BOOLEAN_MASK)) == BOTTOM_MASK) {
return this;
}
switch (mask) {
case NUMBER_MASK:
return commonTypes.getNumberInstance();
case BOOLEAN_MASK:
case TRUE_MASK:
case FALSE_MASK:
return commonTypes.getBooleanInstance();
case STRING_MASK:
return commonTypes.getStringInstance();
}
// 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(commonTypes.getNumberInstanceObjType());
}
if ((mask & STRING_MASK) != 0) {
builder.add(commonTypes.getStringInstanceObjType());
}
if ((mask & BOOLEAN_MASK) != 0) { // may have truthy or falsy
builder.add(commonTypes.getBooleanInstanceObjType());
}
return makeType(
mask & ~(NUMBER_MASK | STRING_MASK | BOOLEAN_MASK),
builder.build(), getTypeVar(), getEnums());
}
static JSType nullAcceptingJoin(JSType t1, JSType t2) {
if (t1 == null) {
return t2;
} else if (t2 == null) {
return t1;
}
return JSType.join(t1, t2);
}
// When joining w/ TOP or UNKNOWN, avoid setting more fields on them, eg, obj.
public static JSType join(JSType lhs, JSType rhs) {
if (lhs.isTop() || rhs.isTop()) {
return TOP;
} else if (lhs.isUnknown() || rhs.isUnknown()) {
return UNKNOWN;
} else if (lhs.isBottom()) {
return rhs;
} else if (rhs.isBottom()) {
return lhs;
}
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 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(newMask, newObjs, newTypevar, ImmutableSet.<EnumType>of());
}
JSType tmpJoin =
makeType(newMask & ~ENUM_MASK, newObjs, newTypevar, ImmutableSet.<EnumType>of());
return makeType(newMask, newObjs, newTypevar,
EnumType.normalizeForJoin(newEnums, tmpJoin));
}
public JSType substituteGenerics(Map<String, JSType> concreteTypes) {
if (isTop()
|| isUnknown()
|| getObjs().isEmpty() && getTypeVar() == null
|| concreteTypes.isEmpty()) {
return this;
}
ImmutableSet.Builder<ObjectType> builder = ImmutableSet.builder();
for (ObjectType obj : getObjs()) {
builder.add(obj.substituteGenerics(concreteTypes));
}
JSType current = makeType(
getMask() & ~TYPEVAR_MASK, builder.build(), null, getEnums());
if ((getMask() & TYPEVAR_MASK) != 0) {
current = JSType.join(current, concreteTypes.containsKey(getTypeVar()) ?
concreteTypes.get(getTypeVar()) : fromTypeVar(getTypeVar()));
}
return current;
}
public JSType substituteGenericsWithUnknown() {
return substituteGenerics(MAP_TO_UNKNOWN);
}
private static void updateTypemap(
Multimap<String, JSType> typeMultimap,
String typeParam, JSType type) {
Set<JSType> typesToRemove = new LinkedHashSet<>();
for (JSType other : typeMultimap.get(typeParam)) {
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;
}
}
for (JSType typeToRemove : typesToRemove) {
typeMultimap.remove(typeParam, typeToRemove);
}
typeMultimap.put(typeParam, type);
}
private static int promoteBoolean(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) {
if (t1.isUnknown()) {
return t2;
} else if (t2.isUnknown()) {
return t1;
} else if (t1.isTop() && t2.isTop()) {
return TOP;
} else if (t1.isTop() || t2.isTop()) {
return null;
}
if (!t1.getEnums().equals(t2.getEnums())) {
return null;
}
ImmutableSet<EnumType> newEnums = t1.getEnums();
int t1Mask = promoteBoolean(t1.getMask());
int t2Mask = promoteBoolean(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(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.
* Note that if {@code this} is a union type, some of the union members may
* be ignored if they are not present in {@code other}.
* @return Whether unification succeeded
*/
public boolean unifyWithSubtype(JSType other, List<String> typeParameters,
Multimap<String, JSType> typeMultimap) {
if (this.isUnknown() || this.isTop()) {
return true;
} else if (getMask() == TYPEVAR_MASK
&& typeParameters.contains(getTypeVar())) {
updateTypemap(typeMultimap, getTypeVar(), other);
return true;
} else if (other.isUnknown()) {
return true;
} else if (other.isTop()) {
// T|number doesn't unify with TOP
return false;
}
Set<EnumType> ununifiedEnums = ImmutableSet.of();
if (getEnums().isEmpty()) {
ununifiedEnums = other.getEnums();
} else if (other.getEnums().isEmpty()) {
ununifiedEnums = new LinkedHashSet<>();
for (EnumType e : other.getEnums()) {
if (!getEnums().contains(e)) {
ununifiedEnums.add(e);
}
}
}
Set<ObjectType> ununifiedObjs = new LinkedHashSet<>(other.getObjs());
// Each obj in this must unify w/ exactly one obj in other.
// However, we don't check that two different objects of this don't unify
// with the same other type.
// Fancy cases are unfortunately iteration-order dependent, eg,
// Foo<number>|Foo<string> may or may not unify with Foo<T>|Foo<string>
for (ObjectType targetObj : getObjs()) {
for (ObjectType sourceObj : other.getObjs()) {
if (targetObj.unifyWithSubtype(sourceObj, typeParameters, typeMultimap)) {
ununifiedObjs.remove(sourceObj);
}
}
}
String thisTypevar = getTypeVar();
String otherTypevar = other.getTypeVar();
if (thisTypevar == null || !typeParameters.contains(thisTypevar)) {
return ununifiedObjs.isEmpty() && ununifiedEnums.isEmpty()
&& (otherTypevar == null || otherTypevar.equals(thisTypevar))
&& getMask() == (getMask() | other.getMask());
} else {
// this is (T | ...)
int templateMask = BOTTOM_MASK;
int thisScalarBits = getMask() & ~NON_SCALAR_MASK & ~TYPEVAR_MASK;
int otherScalarBits = other.getMask() & ~NON_SCALAR_MASK;
templateMask |= otherScalarBits & ~thisScalarBits;
if (templateMask == BOTTOM_MASK) {
// nothing left in other to assign to thisTypevar, so don't update typemap
return ununifiedObjs.isEmpty() && ununifiedEnums.isEmpty();
}
JSType templateType = makeType(
promoteBoolean(templateMask),
ImmutableSet.copyOf(ununifiedObjs),
otherTypevar,
ImmutableSet.copyOf(ununifiedEnums));
updateTypemap(typeMultimap, getTypeVar(), templateType);
return true;
}
}
// TODO(dimvar): Now that we don't have locations, we may be able to combine
// specialize and meet into a single function.
// Specialize might still not be symmetric however, b/c of truthy/falsy.
public JSType specialize(JSType other) {
if (other.isTop() || other.isUnknown() || this == other) {
return this;
} else if (other.isTruthy()) {
return makeTruthy();
} else if (other.isFalsy()) {
return makeFalsy();
} else if (this.isTop() || this.isUnknown()) {
return other;
}
int newMask = getMask() & other.getMask();
String newTypevar;
if (Objects.equals(getTypeVar(), other.getTypeVar())) {
newTypevar = getTypeVar();
} else {
newTypevar = null;
newMask &= ~TYPEVAR_MASK;
}
return meetEnums(
newMask, getMask() | other.getMask(),
ObjectType.specializeSet(getObjs(), other.getObjs()),
newTypevar, getObjs(), other.getObjs(), getEnums(), other.getEnums());
}
public static JSType meet(JSType lhs, JSType rhs) {
if (lhs.isTop()) {
return rhs;
} else if (rhs.isTop()) {
return lhs;
} else if (lhs.isUnknown()) {
return rhs;
} else if (rhs.isUnknown()) {
return lhs;
}
int newMask = lhs.getMask() & rhs.getMask();
String newTypevar;
if (Objects.equals(lhs.getTypeVar(), rhs.getTypeVar())) {
newTypevar = lhs.getTypeVar();
} else {
newTypevar = null;
newMask = newMask & ~TYPEVAR_MASK;
}
return meetEnums(
newMask, lhs.getMask() | rhs.getMask(),
ObjectType.meetSets(lhs.getObjs(), rhs.getObjs()),
newTypevar, lhs.getObjs(), rhs.getObjs(),
lhs.getEnums(), rhs.getEnums());
}
/**
* Both {@code meet} and {@code specialize} do the same computation for enums.
* They don't just compute the set of enums; they may modify mask and objs.
* So, both methods finish off by calling this one.
*/
private static JSType meetEnums(int newMask, int unionMask,
ImmutableSet<ObjectType> newObjs, String newTypevar,
ImmutableSet<ObjectType> objs1, ImmutableSet<ObjectType> objs2,
ImmutableSet<EnumType> enums1, ImmutableSet<EnumType> enums2) {
if (Objects.equals(enums1, enums2)) {
return makeType(newMask, newObjs, newTypevar, enums1);
}
ImmutableSet.Builder<EnumType> enumBuilder = ImmutableSet.builder();
ImmutableSet<EnumType> allEnums = EnumType.union(enums1, enums2);
for (EnumType e : allEnums) {
// An enum in the intersection will always be in the result
if (enums1 != null && enums1.contains(e)
&& enums2 != null && enums2.contains(e)) {
enumBuilder.add(e);
continue;
}
// An enum {?} in the union will always be in the result
JSType enumeratedType = e.getEnumeratedType();
if (enumeratedType.isUnknown()) {
enumBuilder.add(e);
continue;
}
// An enum {TypeA} meets with any supertype of TypeA. When this happens,
// we put the enum in the result and remove the supertype.
// The following would be much more complex if we allowed the type of
// an enum to be a union.
if (enumeratedType.getMask() != NON_SCALAR_MASK) {
if ((enumeratedType.getMask() & unionMask) != 0) {
enumBuilder.add(e);
newMask &= ~enumeratedType.getMask();
}
} else if (!objs1.isEmpty() || !objs2.isEmpty()) {
Set<ObjectType> objsToRemove = new LinkedHashSet<>();
ObjectType enumObj = Iterables.getOnlyElement(enumeratedType.getObjs());
for (ObjectType obj1 : objs1) {
if (enumObj.isSubtypeOf(obj1)) {
enumBuilder.add(e);
objsToRemove.add(obj1);
}
}
for (ObjectType obj2 : objs2) {
if (enumObj.isSubtypeOf(obj2)) {
enumBuilder.add(e);
objsToRemove.add(obj2);
}
}
if (!objsToRemove.isEmpty()) {
newObjs = Sets.difference(newObjs, objsToRemove).immutableCopy();
}
}
}
return makeType(newMask, newObjs, newTypevar, enumBuilder.build());
}
private JSType makeTruthy() {
if (this.isTop() || this.isUnknown()) {
return this;
}
return makeType(getMask() & ~NULL_MASK & ~FALSE_MASK & ~UNDEFINED_MASK,
getObjs(), getTypeVar(), getEnums());
}
private JSType makeFalsy() {
if (this.isTop() || this.isUnknown()) {
return this;
}
return makeType(getMask() & ~TRUE_MASK & ~NON_SCALAR_MASK,
ImmutableSet.<ObjectType>of(), getTypeVar(), getEnums());
}
public static JSType plus(JSType lhs, JSType rhs) {
int newtype = (lhs.getMask() | rhs.getMask()) & STRING_MASK;
if ((lhs.getMask() & ~STRING_MASK) != 0
&& (rhs.getMask() & ~STRING_MASK) != 0) {
newtype |= NUMBER_MASK;
}
return makeType(newtype);
}
public JSType negate() {
if (isTop() || isUnknown()) {
return this;
}
if (isTruthy()) {
return FALSY;
} else if (isFalsy()) {
return TRUTHY;
}
return UNKNOWN;
}
public JSType toBoolean() {
if (isTruthy()) {
return TRUE_TYPE;
} else if (isFalsy()) {
return FALSE_TYPE;
}
return BOOLEAN;
}
public boolean isNonLooseSubtypeOf(JSType other) {
return isSubtypeOfHelper(false, other);
}
@Override
public boolean isSubtypeOf(TypeI other) {
return isSubtypeOfHelper(true, (JSType) other);
}
private boolean isSubtypeOfHelper(
boolean keepLoosenessOfThis, JSType other) {
if (isUnknown() || other.isUnknown() || other.isTop()) {
return true;
}
if (!EnumType.areSubtypes(this, other)) {
return false;
}
int mask = getMask() & ~ENUM_MASK;
if ((mask | other.getMask()) != other.getMask()) {
return false;
}
if (getTypeVar() != null && !getTypeVar().equals(other.getTypeVar())) {
return false;
}
if (getObjs().isEmpty()) {
return true;
}
// Because of optional properties,
// x \le y \iff x \join y = y does not hold.
return ObjectType.isUnionSubtype(
keepLoosenessOfThis, getObjs(), other.getObjs());
}
public JSType removeType(JSType other) {
int otherMask = other.getMask();
Preconditions.checkState(
!other.isTop() && !other.isUnknown()
&& (otherMask & TYPEVAR_MASK) == 0 && (otherMask & ENUM_MASK) == 0);
if (isUnknown()) {
return this;
}
if (isTop()) {
return ALMOST_TOP.removeType(other);
}
int newMask = getMask() & ~otherMask;
if ((otherMask & NON_SCALAR_MASK) == 0) {
return makeType(newMask, getObjs(), getTypeVar(), getEnums());
}
// TODO(dimvar): If objs and enums stay unchanged, reuse, don't recreate.
Preconditions.checkState(other.getObjs().size() == 1,
"Invalid type to remove: %s", other);
ObjectType otherObj = Iterables.getOnlyElement(other.getObjs());
ImmutableSet.Builder<ObjectType> objsBuilder = ImmutableSet.builder();
for (ObjectType obj : getObjs()) {
if (!obj.isSubtypeOf(otherObj)) {
objsBuilder.add(obj);
}
}
ImmutableSet.Builder<EnumType> enumBuilder = ImmutableSet.builder();
for (EnumType e : getEnums()) {
if (!e.getEnumeratedType().isSubtypeOf(other)) {
enumBuilder.add(e);
}
}
return makeType(newMask, objsBuilder.build(), getTypeVar(), enumBuilder.build());
}
public FunctionType getFunTypeIfSingletonObj() {
if (getMask() != NON_SCALAR_MASK || getObjs().size() > 1) {
return null;
}
return Iterables.getOnlyElement(getObjs()).getFunType();
}
public FunctionType getFunType() {
if (getObjs().isEmpty()) {
return null;
}
if (getObjs().size() == 1) { // The common case is fast
return Iterables.getOnlyElement(getObjs()).getFunType();
}
FunctionType result = FunctionType.TOP_FUNCTION;
for (ObjectType obj : getObjs()) {
result = FunctionType.meet(result, obj.getFunType());
}
return result;
}
public NominalType getNominalTypeIfSingletonObj() {
if (getMask() != NON_SCALAR_MASK || getObjs().size() > 1) {
return null;
}
return Iterables.getOnlyElement(getObjs()).getNominalType();
}
public boolean isInterfaceDefinition() {
if (getObjs().isEmpty() || getObjs().size() > 1) {
return false;
}
FunctionType ft = Iterables.getOnlyElement(getObjs()).getFunType();
return ft != null && ft.isInterfaceDefinition();
}
/** Turns the class-less object of this type (if any) into a loose object */
public JSType withLoose() {
if (getObjs().isEmpty()) {
Preconditions.checkState(!getEnums().isEmpty());
return this;
}
return makeType(getMask(), ObjectType.withLooseObjects(getObjs()),
getTypeVar(), getEnums());
}
public JSType getProp(QualifiedName qname) {
if (isBottom() || isUnknown()) {
return UNKNOWN;
}
Preconditions.checkState(!getObjs().isEmpty() || !getEnums().isEmpty(),
"Can't getProp of type %s", this);
return nullAcceptingJoin(
TypeWithPropertiesStatics.getProp(getObjs(), qname),
TypeWithPropertiesStatics.getProp(getEnums(), qname));
}
public JSType getDeclaredProp(QualifiedName qname) {
if (isUnknown()) {
return UNKNOWN;
}
Preconditions.checkState(!getObjs().isEmpty() || !getEnums().isEmpty());
return nullAcceptingJoin(
TypeWithPropertiesStatics.getDeclaredProp(getObjs(), qname),
TypeWithPropertiesStatics.getDeclaredProp(getEnums(), qname));
}
public boolean mayHaveProp(QualifiedName qname) {
return TypeWithPropertiesStatics.mayHaveProp(getObjs(), qname) ||
TypeWithPropertiesStatics.mayHaveProp(getEnums(), qname);
}
public boolean hasProp(QualifiedName qname) {
if (!getObjs().isEmpty()
&& !TypeWithPropertiesStatics.hasProp(getObjs(), qname)) {
return false;
}
if (!getEnums().isEmpty()
&& !TypeWithPropertiesStatics.hasProp(getEnums(), qname)) {
return false;
}
return !getEnums().isEmpty() || !getObjs().isEmpty();
}
public boolean hasConstantProp(QualifiedName pname) {
Preconditions.checkArgument(pname.isIdentifier());
return TypeWithPropertiesStatics.hasConstantProp(getObjs(), pname) ||
TypeWithPropertiesStatics.hasConstantProp(getEnums(), pname);
}
public JSType withoutProperty(QualifiedName qname) {
return getObjs().isEmpty() ?
this :
makeType(getMask(), ObjectType.withoutProperty(getObjs(), qname),
getTypeVar(), getEnums());
}
public JSType withProperty(QualifiedName qname, JSType type) {
Preconditions.checkArgument(type != null);
if (isUnknown() || isBottom() || getObjs().isEmpty()) {
return this;
}
return makeType(getMask(), ObjectType.withProperty(getObjs(), qname, type),
getTypeVar(), getEnums());
}
public JSType withDeclaredProperty(
QualifiedName qname, JSType type, boolean isConstant) {
Preconditions.checkState(!getObjs().isEmpty());
if (type == null && isConstant) {
type = JSType.UNKNOWN;
}
return makeType(getMask(),
ObjectType.withDeclaredProperty(getObjs(), qname, type, isConstant),
getTypeVar(), getEnums());
}
public JSType withPropertyRequired(String pname) {
return (isUnknown() || getObjs().isEmpty()) ?
this :
makeType(getMask(), ObjectType.withPropertyRequired(getObjs(), pname),
getTypeVar(), getEnums());
}
@Override
public String toString() {
if (mockToString) {
return "";
}
return appendTo(new StringBuilder()).toString();
}
public StringBuilder appendTo(StringBuilder builder) {
return typeToString(builder);
}