-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
ObjectType.java
1413 lines (1321 loc) · 50.9 KB
/
ObjectType.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.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
import com.google.javascript.jscomp.newtypes.ObjectsBuilder.ResolveConflictsBy;
import com.google.javascript.rhino.Node;
import java.util.Arrays;
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)
*/
final class ObjectType implements TypeWithProperties {
private final NominalType nominalType;
// If an ObjectType is a namespace, we record the Namespace object created
// during GTI here.
private final Namespace ns;
private final FunctionType fn;
private final boolean isLoose;
private final PersistentMap<String, Property> props;
private final ObjectKind objectKind;
private final JSTypes commonTypes;
static ObjectType createBottomObject(JSTypes commonTypes) {
return new ObjectType(commonTypes, commonTypes.getObjectType(),
Preconditions.checkNotNull(commonTypes.BOTTOM_PROPERTY_MAP),
null, null, false, ObjectKind.UNRESTRICTED);
}
private ObjectType(JSTypes commonTypes, NominalType nominalType,
PersistentMap<String, Property> props, FunctionType fn, Namespace ns,
boolean isLoose, ObjectKind objectKind) {
Preconditions.checkNotNull(commonTypes);
Preconditions.checkNotNull(nominalType);
Preconditions.checkArgument(
fn == null || fn.isQmarkFunction() || fn.isLoose() == isLoose,
"isLoose: %s, fn: %s", isLoose, fn);
Preconditions.checkArgument(FunctionType.isInhabitable(fn));
if (ns != null) {
String name = nominalType.getName();
Preconditions.checkArgument(name.equals(JSTypes.OBJLIT_CLASS_NAME)
|| name.equals("Function") || name.equals("Window"),
"Can't create namespace with nominal type %s", name);
}
Preconditions.checkArgument(!nominalType.isClassy() || !isLoose,
"Cannot create loose objectType with nominal type %s", nominalType);
Preconditions.checkArgument(fn == null || nominalType.isFunction(),
"Cannot create objectType of nominal type %s with function (%s)",
nominalType, fn);
this.commonTypes = commonTypes;
this.nominalType = nominalType;
this.props = isLoose ? loosenProps(props) : props;
this.fn = fn;
this.ns = ns;
this.isLoose = isLoose;
// Don't track @struct-ness/@dict-ness for loose objects
this.objectKind = isLoose ? ObjectKind.UNRESTRICTED : objectKind;
}
// Loose object types may have properties that are also loose objects, eg,
// function f(obj) { obj.a.b.c = 123; }
// This function makes sure we mark these object properties as loose.
private static PersistentMap<String, Property> loosenProps(
PersistentMap<String, Property> props) {
PersistentMap<String, Property> newProps = props;
for (Map.Entry<String, Property> entry : props.entrySet()) {
JSType propType = entry.getValue().getType();
ObjectType objType = propType.getObjTypeIfSingletonObj();
if (objType != null
&& !objType.nominalType.isClassy() && !objType.isLoose()) {
newProps = newProps.with(
entry.getKey(),
Property.make(propType.withLoose(), null));
}
}
return newProps;
}
static ObjectType makeObjectType(JSTypes commonTypes, NominalType nominalType,
PersistentMap<String, Property> props, FunctionType fn, Namespace ns,
boolean isLoose, ObjectKind ok) {
Preconditions.checkNotNull(nominalType);
if (props == null) {
props = PersistentMap.create();
} else if (containsBottomProp(props) || !FunctionType.isInhabitable(fn)) {
return commonTypes.getBottomObject();
}
if (fn != null && !props.containsKey("prototype")
&& (ns == null || ns.getNsProp("prototype") == null)) {
props = props.with("prototype", Property.make(fn.getCommonTypes().UNKNOWN, null));
}
return new ObjectType(commonTypes, nominalType, props, fn, ns, isLoose, ok);
}
static ObjectType fromFunction(FunctionType fn, NominalType fnNominal) {
return makeObjectType(fn.getCommonTypes(),
fnNominal, null, fn, null, fn.isLoose(), ObjectKind.UNRESTRICTED);
}
static ObjectType fromNominalType(NominalType cl) {
return makeObjectType(cl.getCommonTypes(), cl, null, null, null, false, cl.getObjectKind());
}
/** Construct an object with the given declared properties. */
static ObjectType fromProperties(JSTypes commonTypes, Map<String, Property> oldProps) {
PersistentMap<String, Property> newProps = PersistentMap.create();
for (Map.Entry<String, Property> entry : oldProps.entrySet()) {
Property prop = entry.getValue();
if (prop.getDeclaredType().isBottom()) {
return commonTypes.getBottomObject();
}
newProps = newProps.with(entry.getKey(), prop);
}
return new ObjectType(commonTypes, commonTypes.getObjectType(), newProps,
null, null, false, ObjectKind.UNRESTRICTED);
}
JSTypes getCommonTypes() {
return this.commonTypes;
}
boolean isInhabitable() {
return this != this.commonTypes.getBottomObject();
}
static boolean containsBottomProp(PersistentMap<String, Property> props) {
for (Property p : props.values()) {
if (p.getType().isBottom()) {
return true;
}
}
return false;
}
boolean isStruct() {
return objectKind.isStruct();
}
boolean isLoose() {
return isLoose;
}
boolean isDict() {
return objectKind.isDict();
}
boolean isFunctionWithProperties() {
return this.fn != null && hasNonPrototypeProperties();
}
boolean isInterfaceInstance() {
return this.nominalType != null && this.nominalType.isInterface();
}
boolean isNamespace() {
return this.ns != null;
}
private boolean hasNonPrototypeProperties() {
for (String pname : this.props.keySet()) {
if (!pname.equals("prototype")) {
return true;
}
}
return this.ns != null;
}
static ImmutableSet<ObjectType> withLooseObjects(Set<ObjectType> objs) {
ImmutableSet.Builder<ObjectType> newObjs = ImmutableSet.builder();
for (ObjectType obj : objs) {
newObjs.add(obj.withLoose());
}
return newObjs.build();
}
private static boolean hasOnlyBuiltinProps(ObjectType obj, ObjectType someBuiltinObj) {
for (String pname : obj.props.keySet()) {
if (!someBuiltinObj.mayHaveProp(new QualifiedName(pname))) {
return false;
}
}
return true;
}
// Crude heuristic to decide whether a loose object is actually a scalar type
// and methods have been called on it.
// Does not apply to too-common properties such as toString (and for this
// reason it doesn't apply to booleans).
// Only uses property names; change it to use types if precision isn't
// satisfactory.
static JSType mayTurnLooseObjectToScalar(JSType t, JSTypes commonTypes) {
ObjectType obj = t.getObjTypeIfSingletonObj();
if (obj == null || !obj.isLoose() || obj.props.isEmpty() || obj.fn != null
|| hasOnlyBuiltinProps(obj, t.getCommonTypes().getTopObjectType())
|| hasOnlyBuiltinProps(
obj, commonTypes.getArrayInstance().getObjTypeIfSingletonObj())) {
return t;
}
if (hasOnlyBuiltinProps(obj, commonTypes.getNumberInstanceObjType())) {
return t.getCommonTypes().NUMBER;
}
if (hasOnlyBuiltinProps(obj, commonTypes.getStringInstanceObjType())) {
return t.getCommonTypes().STRING;
}
return t;
}
// Trade-offs about property behavior on loose object types:
// We never mark properties as optional on loose objects. The reason is that
// we cannot know for sure when a property is optional or not.
// Eg, when we see an assignment to a loose obj
// obj.p1 = 123;
// we cannot know if obj already has p1, or if this is a property creation.
// If the assignment is inside an IF branch, we should not say after the IF
// that p1 is optional. But as a consequence, this means that any property we
// see on a loose object might be optional. That's why we don't warn about
// possibly-inexistent properties on loose objects.
// Last, say we infer a loose object type with a property p1 for a formal
// parameter of a function f. If we pass a non-loose object to f that does not
// have a p1, we warn. This may create spurious warnings, if p1 is optional,
// but mostly it catches real bugs.
private ObjectType withLoose() {
if (isTopObject()) {
return this.commonTypes.getLooseTopObjectType();
}
if (isLoose()
// Don't loosen nominal types
|| this.nominalType != null && this.nominalType.isClassy()
// Don't loosen namespaces
|| this.ns != null) {
return this;
}
FunctionType fn = this.fn == null ? null : this.fn.withLoose();
PersistentMap<String, Property> newProps = PersistentMap.create();
for (Map.Entry<String, Property> propsEntry : this.props.entrySet()) {
String pname = propsEntry.getKey();
Property prop = propsEntry.getValue();
// It's wrong to warn about a possibly absent property on loose objects.
newProps = newProps.with(pname, prop.withRequired());
}
// No need to call makeObjectType; we know that the new object is inhabitable.
return new ObjectType(
this.commonTypes, this.nominalType, newProps, fn, null, true, this.objectKind);
}
ObjectType withFunction(FunctionType ft, NominalType fnNominal) {
Preconditions.checkState(this.isNamespace());
Preconditions.checkState(!ft.isLoose() || ft.isQmarkFunction());
ObjectType obj = makeObjectType(
this.commonTypes, fnNominal, this.props, ft, this.ns, false, this.objectKind);
this.ns.updateNamespaceType(JSType.fromObjectType(obj));
return obj;
}
static ImmutableSet<ObjectType> withoutProperty(
Set<ObjectType> objs, QualifiedName qname) {
ImmutableSet.Builder<ObjectType> newObjs = ImmutableSet.builder();
for (ObjectType obj : objs) {
newObjs.add(obj.withProperty(qname, null));
}
return newObjs.build();
}
// When type is null, this method removes the property.
// If the property is already declared, but isDeclared is false, be careful
// to not un-declare it.
// If the property is already constant, but isConstant is false, be careful
// to not un-const it.
private ObjectType withPropertyHelper(QualifiedName qname, JSType type,
boolean isDeclared, boolean isConstant) {
// TODO(dimvar): We do some short-circuiting based on the declared type,
// but maybe we can do more based also on the existing inferred type (?)
PersistentMap<String, Property> newProps = this.props;
if (qname.isIdentifier()) {
String pname = qname.getLeftmostName();
JSType declType = getDeclaredProp(qname);
if (type == null) {
type = declType;
}
if (declType != null) {
isDeclared = true;
if (hasConstantProp(qname)) {
isConstant = true;
}
if (type != null && !type.isSubtypeOf(declType, SubtypeCache.create())) {
// Can happen in inheritance-related type errors.
// Not sure what the best approach is.
// For now, just forget the inferred type.
type = declType;
}
}
if (type == null && declType == null) {
newProps = newProps.without(pname);
} else if (!type.equals(declType)) {
if (isDeclared && declType == null) {
declType = type;
}
// If we're about to override an existing property, then preserve its defsite.
Node defsite = null;
if (hasProp(qname)) {
defsite = getLeftmostProp(qname).getDefSite();
}
newProps = newProps.with(pname,
isConstant ?
Property.makeConstant(defsite, type, declType) :
Property.makeWithDefsite(defsite, type, isDeclared ? declType : null));
}
} else { // This has a nested object
String objName = qname.getLeftmostName();
QualifiedName objQname = new QualifiedName(objName);
if (!mayHaveProp(objQname)) {
Preconditions.checkState(type == null,
"Trying to update property %s on type %s, but sub-property %s does"
+ " not exist", qname, this, objName);
return this;
}
QualifiedName innerProps = qname.getAllButLeftmost();
Property objProp = getLeftmostProp(objQname);
JSType inferred = type == null ?
objProp.getType().withoutProperty(innerProps) :
objProp.getType().withProperty(innerProps, type);
JSType declared = objProp.getDeclaredType();
if (!inferred.equals(declared)) {
newProps = newProps.with(objName, objProp.isOptional() ?
Property.makeOptional(null, inferred, declared) :
Property.make(inferred, declared));
}
}
// check for ref equality to avoid creating a new type
if (newProps == this.props) {
return this;
}
return makeObjectType(this.commonTypes, this.nominalType, newProps,
this.fn, this.ns, this.isLoose, this.objectKind);
}
// When type is null, this method removes the property.
ObjectType withProperty(QualifiedName qname, JSType type) {
return withPropertyHelper(qname, type, false, false);
}
static ImmutableSet<ObjectType> withProperty(
Set<ObjectType> objs, QualifiedName qname, JSType type) {
ImmutableSet.Builder<ObjectType> newObjs = ImmutableSet.builder();
for (ObjectType obj : objs) {
newObjs.add(obj.withProperty(qname, type));
}
return newObjs.build();
}
static ImmutableSet<ObjectType> withDeclaredProperty(Set<ObjectType> objs,
QualifiedName qname, JSType type, boolean isConstant) {
ImmutableSet.Builder<ObjectType> newObjs = ImmutableSet.builder();
for (ObjectType obj : objs) {
newObjs.add(obj.withPropertyHelper(qname, type, true, isConstant));
}
return newObjs.build();
}
private ObjectType withPropertyRequired(String pname) {
Property oldProp = this.props.get(pname);
Property newProp = oldProp == null
? Property.make(this.commonTypes.UNKNOWN, null)
: Property.make(oldProp.getType(), oldProp.getDeclaredType());
return makeObjectType(this.commonTypes, this.nominalType, this.props.with(pname, newProp),
this.fn, this.ns, this.isLoose, this.objectKind);
}
static ImmutableSet<ObjectType> withPropertyRequired(
Set<ObjectType> objs, String pname) {
ImmutableSet.Builder<ObjectType> newObjs = ImmutableSet.builder();
for (ObjectType obj : objs) {
newObjs.add(obj.withPropertyRequired(pname));
}
return newObjs.build();
}
private static PersistentMap<String, Property> meetPropsHelper(
JSTypes commonTypes,
boolean specializeProps1, NominalType resultNominalType,
PersistentMap<String, Property> props1,
PersistentMap<String, Property> props2) {
Preconditions.checkNotNull(resultNominalType);
PersistentMap<String, Property> newProps = props1;
for (Map.Entry<String, Property> propsEntry : props1.entrySet()) {
String pname = propsEntry.getKey();
Property otherProp = resultNominalType.getProp(pname);
if (otherProp != null) {
newProps = addOrRemoveProp(
specializeProps1, newProps, pname, otherProp, propsEntry.getValue());
if (newProps == commonTypes.BOTTOM_PROPERTY_MAP) {
return commonTypes.BOTTOM_PROPERTY_MAP;
}
}
}
for (Map.Entry<String, Property> propsEntry : props2.entrySet()) {
String pname = propsEntry.getKey();
Property prop2 = propsEntry.getValue();
Property newProp;
if (!props1.containsKey(pname)) {
newProp = prop2;
} else {
Property prop1 = props1.get(pname);
if (prop1.equals(prop2)) {
continue;
}
newProp = specializeProps1 ?
prop1.specialize(prop2) :
Property.meet(prop1, prop2);
}
Property otherProp = resultNominalType.getProp(pname);
if (otherProp != null) {
newProps = addOrRemoveProp(specializeProps1, newProps, pname, otherProp, newProp);
if (newProps == commonTypes.BOTTOM_PROPERTY_MAP) {
return commonTypes.BOTTOM_PROPERTY_MAP;
}
} else {
if (newProp.getType().isBottom()) {
return commonTypes.BOTTOM_PROPERTY_MAP;
}
newProps = newProps.with(pname, newProp);
}
}
return newProps;
}
private static PersistentMap<String, Property> addOrRemoveProp(
boolean specializeProps1, PersistentMap<String, Property> props,
String pname, Property nomProp, Property objProp) {
JSType nomPropType = nomProp.getType();
Property newProp = specializeProps1
? nomProp.specialize(objProp)
: Property.meet(nomProp, objProp);
JSType newPropType = newProp.getType();
if (newPropType.isBottom()) {
return newPropType.getCommonTypes().BOTTOM_PROPERTY_MAP;
}
if (!newPropType.isUnknown()
&& newPropType.isSubtypeOf(nomPropType, SubtypeCache.create())
&& !newPropType.equals(nomPropType)) {
return props.with(pname, newProp);
}
return props.without(pname);
}
private static Property getProp(Map<String, Property> props, NominalType nom, String pname) {
if (props.containsKey(pname)) {
return props.get(pname);
} else if (nom != null) {
return nom.getProp(pname);
}
return null;
}
// This method needs the nominal types because otherwise a property may become
// optional by mistake after the join.
// joinPropsLoosely doesn't need that, because we don't create optional props
// on loose types.
private static PersistentMap<String, Property> joinProps(
Map<String, Property> props1, Map<String, Property> props2,
NominalType nom1, NominalType nom2) {
PersistentMap<String, Property> newProps = PersistentMap.create();
for (String pname : Sets.union(props1.keySet(), props2.keySet())) {
Property prop1 = getProp(props1, nom1, pname);
Property prop2 = getProp(props2, nom2, pname);
Property newProp = null;
if (prop1 == null) {
newProp = prop2.withOptional();
} else if (prop2 == null) {
newProp = prop1.withOptional();
} else {
newProp = Property.join(prop1, prop2);
}
newProps = newProps.with(pname, newProp);
}
return newProps;
}
private static PersistentMap<String, Property> joinPropsLoosely(
JSTypes commonTypes,
Map<String, Property> props1, Map<String, Property> props2) {
PersistentMap<String, Property> newProps = PersistentMap.create();
for (Map.Entry<String, Property> propsEntry : props1.entrySet()) {
String pname = propsEntry.getKey();
if (!props2.containsKey(pname)) {
newProps = newProps.with(pname, propsEntry.getValue().withRequired());
}
if (newProps == commonTypes.BOTTOM_PROPERTY_MAP) {
return commonTypes.BOTTOM_PROPERTY_MAP;
}
}
for (Map.Entry<String, Property> propsEntry : props2.entrySet()) {
String pname = propsEntry.getKey();
Property prop2 = propsEntry.getValue();
if (props1.containsKey(pname)) {
newProps = newProps.with(pname,
Property.join(props1.get(pname), prop2).withRequired());
} else {
newProps = newProps.with(pname, prop2.withRequired());
}
if (newProps == commonTypes.BOTTOM_PROPERTY_MAP) {
return commonTypes.BOTTOM_PROPERTY_MAP;
}
}
return newProps;
}
static boolean isUnionSubtype(boolean keepLoosenessOfThis,
Set<ObjectType> objs1, Set<ObjectType> objs2, SubtypeCache subSuperMap) {
return isUnionSubtypeHelper(
keepLoosenessOfThis, objs1, objs2, subSuperMap, null);
}
static void whyNotUnionSubtypes(boolean keepLoosenessOfThis,
Set<ObjectType> objs1, Set<ObjectType> objs2, SubtypeCache subSuperMap,
MismatchInfo[] boxedInfo) {
Preconditions.checkArgument(boxedInfo.length == 1);
boolean areSubtypes = isUnionSubtypeHelper(
keepLoosenessOfThis, objs1, objs2, subSuperMap, boxedInfo);
Preconditions.checkState(!areSubtypes);
}
private static boolean isUnionSubtypeHelper(boolean keepLoosenessOfThis,
Set<ObjectType> objs1, Set<ObjectType> objs2, SubtypeCache subSuperMap,
MismatchInfo[] boxedInfo) {
for (ObjectType obj1 : objs1) {
boolean foundSupertype = false;
for (ObjectType obj2 : objs2) {
if (obj1.isSubtypeOfHelper(keepLoosenessOfThis, obj2, subSuperMap, null)) {
foundSupertype = true;
break;
}
}
if (!foundSupertype) {
if (boxedInfo != null) {
boxedInfo[0] =
MismatchInfo.makeUnionTypeMismatch(JSType.fromObjectType(obj1));
}
return false;
}
}
return true;
}
boolean isSubtypeOf(ObjectType obj2, SubtypeCache subSuperMap) {
return isSubtypeOfHelper(true, obj2, subSuperMap, null);
}
static void whyNotSubtypeOf(
ObjectType obj1, ObjectType obj2, MismatchInfo[] boxedInfo) {
Preconditions.checkArgument(boxedInfo.length == 1);
boolean areSubtypes =
obj1.isSubtypeOfHelper(true, obj2, SubtypeCache.create(), boxedInfo);
Preconditions.checkState(!areSubtypes);
}
/**
* Required properties are acceptable where an optional is required,
* but not vice versa.
* Optional properties create cycles in the type lattice, eg,
* { } \le { p: num= } and also { p: num= } \le { }.
*/
private boolean isSubtypeOfHelper(boolean keepLoosenessOfThis,
ObjectType other, SubtypeCache subSuperMap, MismatchInfo[] boxedInfo) {
if (other.isTopObject()) {
return true;
}
if ((keepLoosenessOfThis && this.isLoose) || other.isLoose) {
return this.isLooseSubtypeOf(other, subSuperMap);
}
NominalType thisNt = this.nominalType;
NominalType otherNt = other.nominalType;
boolean checkOnlyLocalProps = true;
if (otherNt.isStructuralInterface()) {
if (otherNt.equals(subSuperMap.get(thisNt))) {
return true;
}
subSuperMap = subSuperMap.with(thisNt, otherNt);
if (!thisNt.isNominalSubtypeOf(otherNt)) {
checkOnlyLocalProps = false;
}
// IObject and IArrayLike are treated specially;
// unlike other structural types, we check that the generics match.
if (otherNt.isIObject()) {
if (thisNt.inheritsFromIObjectReflexive()
&& !thisNt.isNominalSubtypeOf(otherNt)) {
return false;
}
if (thisNt.isBuiltinObject() || thisNt.isLiteralObject()) {
return compareRecordTypeToIObject(otherNt, subSuperMap);
}
} else if (otherNt.isIArrayLike()) {
if (thisNt.inheritsFromIObjectReflexive()
&& (!thisNt.getIndexType().isSubtypeOf(this.commonTypes.NUMBER, subSuperMap)
|| !thisNt.getIndexedType().isSubtypeOf(otherNt.getIndexedType(), subSuperMap))) {
return false;
}
}
} else if (!thisNt.isNominalSubtypeOf(otherNt)) {
return false;
}
// If nominalType1 < nominalType2, we only need to check that the
// properties of other are in (obj1 or nominalType1)
Set<String> otherPropNames;
if (checkOnlyLocalProps) {
otherPropNames = other.props.keySet();
} else {
otherPropNames = otherNt.getAllPropsOfInterface();
if (otherPropNames == null) {
// Can't check structural interfaces for subtyping during GlobalTypeInfo
return false;
}
}
if (!arePropertiesSubtypes(other, otherPropNames, subSuperMap, boxedInfo)) {
return false;
}
if (other.fn == null) {
return true;
} else if (this.fn == null) {
// Can only be executed if we have declared types for callable objects.
return false;
}
boolean areFunsSubtypes = this.fn.isSubtypeOf(other.fn, subSuperMap);
if (boxedInfo != null) {
FunctionType.whyNotSubtypeOf(this.fn, other.fn, subSuperMap, boxedInfo);
}
return areFunsSubtypes;
}
// NOTE(dimvar): it's not ideal that the unquoted properties of the
// object literal are checked as part of the IObject type. We want
// a property to either always be accessed with dot or with brackets,
// and checking the unquoted properties against IObject gives the
// impression that we support both kinds of accesses for the same
// property. The alternatives are (none is very satisfactory):
// 1) Don't check any object-literal properties against IObject
// 2) Check all object-literal properties against IObject (what we're currently doing)
// 3) Check only the quoted object-literal properties against IObject.
// This is not great because NTI also checks quoted properties individually
// if the name is known.
// 4) Remember in the property map whether a property name was declared as
// quoted or not. This will likely involve a lot of extra plumbing.
private boolean compareRecordTypeToIObject(
NominalType otherNt, SubtypeCache subSuperMap) {
JSType keyType = otherNt.getIndexType();
JSType valueType = otherNt.getIndexedType();
for (Map.Entry<String, Property> entry : this.props.entrySet()) {
String pname = entry.getKey();
JSType ptype = entry.getValue().getType();
if (keyType.isNumber() && Ints.tryParse(pname) == null) {
return false;
}
if (!keyType.isNumber() && !keyType.isString() && !keyType.isUnknown()) {
return false;
}
if (!ptype.isSubtypeOf(valueType, subSuperMap)) {
return false;
}
}
return true;
}
private boolean arePropertiesSubtypes(ObjectType other,
Set<String> otherPropNames, SubtypeCache subSuperMap,
MismatchInfo[] boxedInfo) {
for (String pname : otherPropNames) {
QualifiedName qname = new QualifiedName(pname);
if (!isPropertySubtype(
pname, this.getLeftmostProp(qname), other.getLeftmostProp(qname),
subSuperMap, boxedInfo)) {
return false;
}
}
if (other.ns != null) {
for (String pname : other.ns.getAllPropsOfNamespace()) {
if (!otherPropNames.contains(pname)) {
QualifiedName qname = new QualifiedName(pname);
if (!isPropertySubtype(
pname, this.getLeftmostProp(qname), other.getLeftmostProp(qname),
subSuperMap, boxedInfo)) {
return false;
}
}
}
}
return true;
}
private static boolean isPropertySubtype(String pname, Property prop1,
Property prop2, SubtypeCache subSuperMap, MismatchInfo[] boxedInfo) {
return boxedInfo != null
? getPropMismatchInfo(pname, prop1, prop2, subSuperMap, boxedInfo)
: isPropertySubtypeHelper(prop1, prop2, subSuperMap);
}
private static boolean isPropertySubtypeHelper(
Property prop1, Property prop2, SubtypeCache subSuperMap) {
if (prop2.isOptional()) {
if (prop1 != null
&& !prop1.getType().isSubtypeOf(prop2.getType(), subSuperMap)) {
return false;
}
} else {
if (prop1 == null || prop1.isOptional() ||
!prop1.getType().isSubtypeOf(prop2.getType(), subSuperMap)) {
return false;
}
}
return true;
}
// Like isPropertySubtypeHelper, but also provides mismatch information
private static boolean getPropMismatchInfo(String pname, Property prop1,
Property prop2, SubtypeCache subSuperMap, MismatchInfo[] boxedInfo) {
Preconditions.checkNotNull(pname);
if (prop2.isOptional()) {
if (prop1 != null
&& !prop1.getType().isSubtypeOf(prop2.getType(), subSuperMap)) {
boxedInfo[0] = MismatchInfo.makePropTypeMismatch(
pname, prop2.getType(), prop1.getType());
return false;
}
} else {
if (prop1 == null) {
boxedInfo[0] = MismatchInfo.makeMissingPropMismatch(pname);
return false;
} else if (prop1.isOptional()) {
boxedInfo[0] = MismatchInfo.makeMaybeMissingPropMismatch(pname);
return false;
} else if (!prop1.getType().isSubtypeOf(prop2.getType(), subSuperMap)) {
boxedInfo[0] = MismatchInfo.makePropTypeMismatch(
pname, prop2.getType(), prop1.getType());
return false;
}
}
return true;
}
// We never infer properties as optional on loose objects,
// and we don't warn about possibly inexistent properties.
boolean isLooseSubtypeOf(ObjectType other, SubtypeCache subSuperMap) {
Preconditions.checkState(isLoose || other.isLoose);
if (other.isTopObject()) {
return true;
}
if (!isLoose) {
for (String pname : other.props.keySet()) {
QualifiedName qname = new QualifiedName(pname);
if (isStruct()) {
if (!mayHaveProp(qname)
|| !getProp(qname).isSubtypeOf(other.getProp(qname), subSuperMap)) {
return false;
}
} else {
if (mayHaveProp(qname)
&& !getProp(qname).isSubtypeOf(other.getProp(qname), subSuperMap)) {
return false;
}
}
}
} else { // this is loose, other may be loose
for (String pname : this.props.keySet()) {
QualifiedName qname = new QualifiedName(pname);
if (other.mayHaveProp(qname)
&& !getProp(qname).isSubtypeOf(other.getProp(qname), subSuperMap)) {
return false;
}
}
}
if (other.fn == null) {
return this.fn == null
|| other.nominalType.isBuiltinObject() || other.isLoose();
} else if (this.fn == null) {
return isLoose;
}
return fn.isLooseSubtypeOf(other.fn);
}
ObjectType specialize(ObjectType other) {
Preconditions.checkState(
areRelatedNominalTypes(this.nominalType, other.nominalType));
if (isTopObject() && other.objectKind.isUnrestricted()) {
return other;
}
if (this.ns != null) {
return specializeNamespace(other);
}
NominalType resultNomType = NominalType.pickSubclass(this.nominalType, other.nominalType);
if (resultNomType.isClassy()) {
Preconditions.checkState(this.fn == null && other.fn == null);
PersistentMap<String, Property> newProps =
meetPropsHelper(this.commonTypes, true, resultNomType, this.props, other.props);
if (newProps == this.commonTypes.BOTTOM_PROPERTY_MAP) {
return this.commonTypes.getBottomObject();
}
return new ObjectType(
this.commonTypes, resultNomType, newProps, null, this.ns, false, this.objectKind);
}
FunctionType thisFn = this.fn;
boolean isLoose = this.isLoose;
if (resultNomType.isFunction() && this.fn == null) {
thisFn = other.fn;
isLoose = other.fn.isLoose();
}
PersistentMap<String, Property> newProps =
meetPropsHelper(this.commonTypes, true, resultNomType, this.props, other.props);
if (newProps == this.commonTypes.BOTTOM_PROPERTY_MAP) {
return this.commonTypes.getBottomObject();
}
FunctionType newFn = thisFn == null ? null : thisFn.specialize(other.fn);
if (!FunctionType.isInhabitable(newFn)) {
return this.commonTypes.getBottomObject();
}
return new ObjectType(
this.commonTypes, resultNomType, newProps, newFn, this.ns, isLoose, this.objectKind);
}
// If obj represents a type of the form {p1: p2: {... {p_n: A}}}
// then return the path p1,p2,...,p_n. Otherwise, return null.
private static QualifiedName getPropertyPath(ObjectType obj) {
if (obj.props.size() != 1) {
return null;
}
Map.Entry<String, Property> entry = obj.props.entrySet().iterator().next();
QualifiedName leftmostPname = new QualifiedName(entry.getKey());
ObjectType propAsObj = entry.getValue().getType().getObjTypeIfSingletonObj();
if (propAsObj == null) {
return leftmostPname;
}
QualifiedName restPath = getPropertyPath(propAsObj);
if (restPath == null) {
return leftmostPname;
}
return QualifiedName.join(leftmostPname, restPath);
}
// Specializing namespace types is very expensive; not just the operation
// itself, but also the fact that you create a large type that you flow around
// later and many other expensive type operations happen on it.
// Therefore, we only specialize namespace types in a very specific case: to
// narrow down a mutable namespace field that has a union type, eg,
// if (goog.bar.baz !== null) { ... }
ObjectType specializeNamespace(ObjectType other) {
Preconditions.checkNotNull(this.ns);
if (this == other
|| other.ns != null
|| !other.nominalType.equals(this.commonTypes.getObjectType())) {
return this;
}
QualifiedName propPath = getPropertyPath(other);
if (propPath == null) {
return this;
}
JSType otherPropType = other.getProp(propPath);
JSType thisPropType = mayHaveProp(propPath) ? getProp(propPath) : null;
JSType newPropType =
thisPropType == null ? null : thisPropType.specialize(otherPropType);
if (thisPropType != null
// Don't specialize for things like: if (goog.DEBUG) { ... }
&& thisPropType.isUnion()
&& !newPropType.isBottom()
&& newPropType.isSubtypeOf(thisPropType)
&& !thisPropType.isSubtypeOf(newPropType)) {
return withProperty(propPath, newPropType);
}
return this;
}
private boolean isTopObject() {
// Reference equality because we want to make sure that we only ever create
// one top object type.
return this == this.commonTypes.getTopObjectType();
}
private boolean isBottomObject() {
// Reference equality because we want to make sure that we only ever create
// one bottom object type.
return this == this.commonTypes.getBottomObject();
}
static ObjectType meet(ObjectType obj1, ObjectType obj2) {
Preconditions.checkState(areRelatedNominalTypes(obj1.nominalType, obj2.nominalType));
if (obj1.isTopObject() || obj2.isBottomObject()) {
return obj2;
} else if (obj2.isTopObject() || obj1.isBottomObject()) {
return obj1;
}
JSTypes commonTypes = obj1.commonTypes;
NominalType resultNomType = NominalType.pickSubclass(obj1.nominalType, obj2.nominalType);
FunctionType fn = FunctionType.meet(obj1.fn, obj2.fn);
if (!FunctionType.isInhabitable(fn)) {
return commonTypes.getBottomObject();
}
boolean isLoose = obj1.isLoose && obj2.isLoose || fn != null && fn.isLoose();
if (resultNomType.isFunction() && fn == null) {
fn = obj1.fn == null ? obj2.fn : obj1.fn;
isLoose = fn.isLoose();
}
PersistentMap<String, Property> props;
if (isLoose) {
props = joinPropsLoosely(commonTypes, obj1.props, obj2.props);
} else {
props = meetPropsHelper(commonTypes, false, resultNomType, obj1.props, obj2.props);
}
if (props == commonTypes.BOTTOM_PROPERTY_MAP) {
return commonTypes.getBottomObject();
}
ObjectKind ok = ObjectKind.meet(obj1.objectKind, obj2.objectKind);
Namespace resultNs = Objects.equals(obj1.ns, obj2.ns) ? obj1.ns : null;
return new ObjectType(commonTypes, resultNomType, props, fn, resultNs, isLoose, ok);
}
static ObjectType join(ObjectType obj1, ObjectType obj2) {
if (obj1.isTopObject() || obj2.isTopObject()) {
return obj1.commonTypes.getTopObjectType();
}
if (obj1.equals(obj2)) {
return obj1;
}
NominalType nt1 = obj1.nominalType;
NominalType nt2 = obj2.nominalType;
Preconditions.checkState(nt1.isRawSubtypeOf(nt2) || nt2.isRawSubtypeOf(nt1));
JSTypes commonTypes = obj1.commonTypes;
boolean isLoose = obj1.isLoose || obj2.isLoose;
FunctionType fn = FunctionType.join(obj1.fn, obj2.fn);
PersistentMap<String, Property> props;
if (isLoose) {
fn = fn == null ? null : fn.withLoose();
props = joinPropsLoosely(commonTypes, obj1.props, obj2.props);
} else {
props = joinProps(obj1.props, obj2.props, nt1, nt2);
}
NominalType nominal = NominalType.pickSuperclass(nt1, nt2);
if (nominal.isBuiltinObject() && fn != null) {
if (isLoose) {
nominal = obj1.commonTypes.getFunctionType();
} else {
// NOTE(dimvar): we don't have a unit test that triggers this case,
// but it happens in our regression tests.
fn = null;
}
}
Namespace ns = Objects.equals(obj1.ns, obj2.ns) ? obj1.ns : null;
return makeObjectType(commonTypes, nominal, props, fn, ns, isLoose,
ObjectKind.join(obj1.objectKind, obj2.objectKind));
}
static ImmutableSet<ObjectType> joinSets(
ImmutableSet<ObjectType> objs1, ImmutableSet<ObjectType> objs2) {
if (objs1.isEmpty()) {
return objs2;
} else if (objs2.isEmpty()) {
return objs1;
}
ObjectType[] objs1Arr = objs1.toArray(new ObjectType[0]);
ObjectType[] keptFrom1 = Arrays.copyOf(objs1Arr, objs1Arr.length);
ObjectsBuilder newObjs = new ObjectsBuilder(ResolveConflictsBy.JOIN);
for (ObjectType obj2 : objs2) {
boolean addedObj2 = false;
for (int i = 0; i < objs1Arr.length; i++) {
ObjectType obj1 = objs1Arr[i];
NominalType nt1 = obj1.nominalType;
NominalType nt2 = obj2.nominalType;
if (areRelatedNominalTypes(nt1, nt2)) {
if ((nt2.isBuiltinObject() && nt1 != null