-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
JSType.java
2113 lines (1856 loc) · 67.3 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
/*
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Bob Jervis
* Google Inc.
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package com.google.javascript.rhino.jstype;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.errorprone.annotations.ForOverride;
import com.google.javascript.rhino.ErrorReporter;
import com.google.javascript.rhino.JSDocInfo;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Objects;
import javax.annotation.Nullable;
/**
* Represents JavaScript value types.
*
* <p>Types are split into two separate families: value types and object types.
*
* <p>A special {@link UnknownType} exists to represent a wildcard type on which no information can
* be gathered. In particular, it can assign to everyone, is a subtype of everyone (and everyone is
* a subtype of it).
*
* <p>If you remove the {@link UnknownType}, the set of types in the type system forms a lattice
* with the {@link #isSubtype} relation defining the partial order of types. All types are united at
* the top of the lattice by the {@link AllType} and at the bottom by the {@link NoType}.
*
* <p>
*
*/
public abstract class JSType implements Serializable {
private static final long serialVersionUID = 1L;
@SuppressWarnings("ReferenceEquality")
static final boolean areIdentical(JSType a, JSType b) {
return a == b;
}
private boolean resolved = false;
private JSType resolveResult = null;
protected TemplateTypeMap templateTypeMap;
private boolean hashCodeInProgress = false;
private boolean inTemplatedCheckVisit = false;
private static final CanCastToVisitor CAN_CAST_TO_VISITOR =
new CanCastToVisitor();
private static final ImmutableSet<String> BIVARIANT_TYPES =
ImmutableSet.of("Object", "IArrayLike", "Array");
final JSTypeRegistry registry;
JSType(JSTypeRegistry registry) {
this(registry, null);
}
JSType(JSTypeRegistry registry, TemplateTypeMap templateTypeMap) {
this.registry = registry;
this.templateTypeMap = templateTypeMap == null ?
registry.createTemplateTypeMap(null, null) : templateTypeMap;
}
/**
* Utility method for less verbose code.
*/
JSType getNativeType(JSTypeNative typeId) {
return registry.getNativeType(typeId);
}
/**
* Gets the docInfo for this type. By default, documentation cannot be
* attached to arbitrary types. This must be overridden for
* programmer-defined types.
*/
public JSDocInfo getJSDocInfo() {
return null;
}
/**
* Returns a user meaningful label for the JSType instance. For example,
* Functions and Enums will return their declaration name (if they have one).
* Some types will not have a meaningful display name. Calls to
* hasDisplayName() will return true IFF getDisplayName() will return null
* or a zero length string.
*
* @return the display name of the type, or null if one is not available
*/
public String getDisplayName() {
return null;
}
/**
* @return true if the JSType has a user meaningful label.
*/
public boolean hasDisplayName() {
String displayName = getDisplayName();
return displayName != null && !displayName.isEmpty();
}
/** A tristate value returned from canPropertyBeDefined. */
public enum HasPropertyKind {
ABSENT, // The property is not known to be part of this type
KNOWN_PRESENT, // The properties is known to be defined on a type or its super types
MAYBE_PRESENT; // The property is loosely associated with a type, typically one of its subtypes
public static HasPropertyKind of(boolean has) {
return has ? KNOWN_PRESENT : ABSENT;
}
}
/**
* Checks whether the property is present on the object.
* @param pname The property name.
*/
public HasPropertyKind getPropertyKind(String pname) {
return getPropertyKind(pname, true);
}
/**
* Checks whether the property is present on the object.
* @param pname The property name.
* @param autobox Whether to check for the presents on an autoboxed type
*/
public HasPropertyKind getPropertyKind(String pname, boolean autobox) {
return HasPropertyKind.ABSENT;
}
/**
* Checks whether the property is present on the object.
* @param pname The property name.
*/
public final boolean hasProperty(String pname) {
return !getPropertyKind(pname, false).equals(HasPropertyKind.ABSENT);
}
public boolean isNoType() {
return false;
}
public boolean isNoResolvedType() {
return false;
}
public final boolean isUnresolved() {
return isNoResolvedType();
}
public final boolean isUnresolvedOrResolvedUnknown() {
return isNoResolvedType() || (isNamedType() && isUnknownType());
}
public boolean isNoObjectType() {
return false;
}
public final boolean isEmptyType() {
return isNoType()
|| isNoObjectType()
|| isNoResolvedType()
|| areIdentical(this, registry.getNativeFunctionType(JSTypeNative.LEAST_FUNCTION_TYPE));
}
public boolean isNumberObjectType() {
return false;
}
public boolean isNumberValueType() {
return false;
}
/** Whether this is the prototype of a function. */
// TODO(sdh): consider renaming this to isPrototypeObject.
public boolean isFunctionPrototypeType() {
return false;
}
public boolean isStringObjectType() {
return false;
}
public boolean isSymbolObjectType() {
return false;
}
boolean isTheObjectType() {
return false;
}
public boolean isStringValueType() {
return false;
}
public boolean isSymbolValueType() {
return false;
}
/**
* Tests whether the type is a string (value or Object).
* @return <code>this <: (String, string)</code>
*/
public final boolean isString() {
return isSubtypeOf(
getNativeType(JSTypeNative.STRING_VALUE_OR_OBJECT_TYPE));
}
/**
* Tests whether the type is a number (value or Object).
* @return <code>this <: (Number, number)</code>
*/
public final boolean isNumber() {
return isSubtypeOf(
getNativeType(JSTypeNative.NUMBER_VALUE_OR_OBJECT_TYPE));
}
public final boolean isSymbol() {
return isSubtypeOf(
getNativeType(JSTypeNative.SYMBOL_VALUE_OR_OBJECT_TYPE));
}
public boolean isArrayType() {
return false;
}
public boolean isBooleanObjectType() {
return false;
}
public boolean isBooleanValueType() {
return false;
}
public boolean isRegexpType() {
return false;
}
public boolean isDateType() {
return false;
}
public boolean isNullType() {
return false;
}
public boolean isVoidType() {
return false;
}
public boolean isAllType() {
return false;
}
public boolean isUnknownType() {
return false;
}
public final boolean isSomeUnknownType() {
// OTI's notion of isUnknownType already accounts for looseness (see override in ObjectType).
return isUnknownType();
}
public boolean isCheckedUnknownType() {
return false;
}
public final boolean isUnionType() {
return toMaybeUnionType() != null;
}
public boolean isFullyInstantiated() {
return getTemplateTypeMap().isFull();
}
public boolean isPartiallyInstantiated() {
return getTemplateTypeMap().isPartiallyFull();
}
/**
* Returns true iff {@code this} can be a {@code struct}.
* UnionType overrides the method, assume {@code this} is not a union here.
*/
public boolean isStruct() {
if (isObject()) {
ObjectType objType = toObjectType();
ObjectType iproto = objType.getImplicitPrototype();
// For the case when a @struct constructor is assigned to a function's
// prototype property
if (iproto != null && iproto.isStruct()) {
return true;
}
FunctionType ctor = objType.getConstructor();
// This test is true for object literals
if (ctor == null) {
JSDocInfo info = objType.getJSDocInfo();
return info != null && info.makesStructs();
} else {
return ctor.makesStructs();
}
}
return false;
}
/**
* Returns true iff {@code this} can be a {@code dict}.
* UnionType overrides the method, assume {@code this} is not a union here.
*/
public boolean isDict() {
if (isObject()) {
ObjectType objType = toObjectType();
ObjectType iproto = objType.getImplicitPrototype();
// For the case when a @dict constructor is assigned to a function's
// prototype property
if (iproto != null && iproto.isDict()) {
return true;
}
FunctionType ctor = objType.getConstructor();
// This test is true for object literals
if (ctor == null) {
JSDocInfo info = objType.getJSDocInfo();
return info != null && info.makesDicts();
} else {
return ctor.makesDicts();
}
}
return false;
}
public final boolean isLiteralObject() {
if (this instanceof PrototypeObjectType) {
return ((PrototypeObjectType) this).isAnonymous();
}
return false;
}
public JSType getGreatestSubtypeWithProperty(String propName) {
return this.registry.getGreatestSubtypeWithProperty(this, propName);
}
/**
* Downcasts this to a UnionType, or returns null if this is not a UnionType.
*
* Named in honor of Haskell's Maybe type constructor.
*/
public UnionType toMaybeUnionType() {
return null;
}
/** Returns true if this is a global this type. */
public final boolean isGlobalThisType() {
return areIdentical(this, registry.getNativeType(JSTypeNative.GLOBAL_THIS));
}
/** Returns true if toMaybeFunctionType returns a non-null FunctionType. */
public final boolean isFunctionType() {
return toMaybeFunctionType() != null;
}
/**
* Downcasts this to a FunctionType, or returns null if this is not a function.
*
* <p>For the purposes of this function, we define a MaybeFunctionType as any type in the
* sub-lattice { x | LEAST_FUNCTION_TYPE <= x <= GREATEST_FUNCTION_TYPE } This definition
* excludes bottom types like NoType and NoObjectType.
*
* <p>This definition is somewhat arbitrary and axiomatic, but this is the definition that makes
* the most sense for the most callers.
*/
@SuppressWarnings("AmbiguousMethodReference")
public FunctionType toMaybeFunctionType() {
return null;
}
/** Returns this object cast to FunctionType or throws an exception if it isn't a FunctionType. */
public FunctionType assertFunctionType() {
FunctionType result = checkNotNull(toMaybeFunctionType(), "not a FunctionType: %s", this);
return result;
}
/** Returns this object cast to ObjectType or throws an exception if it isn't an ObjectType. */
public ObjectType assertObjectType() {
ObjectType result = checkNotNull(toMaybeObjectType(), "Not an ObjectType: %s", this);
return result;
}
/** Null-safe version of toMaybeFunctionType(). */
@SuppressWarnings("AmbiguousMethodReference")
public static FunctionType toMaybeFunctionType(JSType type) {
return type == null ? null : type.toMaybeFunctionType();
}
public final boolean isEnumElementType() {
return toMaybeEnumElementType() != null;
}
public final JSType getEnumeratedTypeOfEnumElement() {
EnumElementType e = toMaybeEnumElementType();
return e == null ? null : e.getPrimitiveType();
}
/**
* Downcasts this to an EnumElementType, or returns null if this is not an EnumElementType.
*/
public EnumElementType toMaybeEnumElementType() {
return null;
}
// TODO(sdh): Consider changing this to isEnumObjectType(), though this would be inconsistent with
// the EnumType class and toMaybeEnumType(), so we would need to consider changing them, too.
public boolean isEnumType() {
return toMaybeEnumType() != null;
}
/**
* Downcasts this to an EnumType, or returns null if this is not an EnumType.
*/
public EnumType toMaybeEnumType() {
return null;
}
public boolean isNamedType() {
return toMaybeNamedType() != null;
}
public NamedType toMaybeNamedType() {
return null;
}
public boolean isRecordType() {
return toMaybeRecordType() != null;
}
public boolean isStructuralInterface() {
return false;
}
public boolean isStructuralType() {
return false;
}
/**
* Downcasts this to a RecordType, or returns null if this is not
* a RecordType.
*/
public RecordType toMaybeRecordType() {
return null;
}
public final boolean isTemplatizedType() {
return toMaybeTemplatizedType() != null;
}
public final boolean isGenericObjectType() {
return isTemplatizedType();
}
/**
* Downcasts this to a TemplatizedType, or returns null if this is not
* a function.
*/
public TemplatizedType toMaybeTemplatizedType() {
return null;
}
public final boolean isTemplateType() {
return toMaybeTemplateType() != null;
}
public final boolean isTypeVariable() {
return isTemplateType();
}
/**
* Downcasts this to a TemplateType, or returns null if this is not
* a function.
*/
public TemplateType toMaybeTemplateType() {
return null;
}
public boolean hasAnyTemplateTypes() {
if (!this.inTemplatedCheckVisit) {
this.inTemplatedCheckVisit = true;
boolean result = hasAnyTemplateTypesInternal();
this.inTemplatedCheckVisit = false;
return result;
} else {
// prevent infinite recursion, this is "not yet".
return false;
}
}
boolean hasAnyTemplateTypesInternal() {
return templateTypeMap.hasAnyTemplateTypesInternal();
}
/**
* Returns the template type map associated with this type.
*/
public TemplateTypeMap getTemplateTypeMap() {
return templateTypeMap;
}
public final ImmutableSet<JSType> getTypeParameters() {
ImmutableSet.Builder<JSType> params = ImmutableSet.builder();
for (TemplateType type : getTemplateTypeMap().getTemplateKeys()) {
params.add(type);
}
return params.build();
}
/**
* Extends the template type map associated with this type, merging in the
* keys and values of the specified map.
*/
public void extendTemplateTypeMap(TemplateTypeMap otherMap) {
templateTypeMap = templateTypeMap.extend(otherMap);
}
/**
* Tests whether this type is an {@code Object}, or any subtype thereof.
* @return <code>this <: Object</code>
*/
public boolean isObject() {
return false;
}
/**
* Tests whether this type is an {@code Object}, or any subtype thereof.
*
* @return <code>this <: Object</code>
*/
public final boolean isObjectType() {
return isObject();
}
/**
* Whether this type is a {@link FunctionType} that is a constructor or a
* named type that points to such a type.
*/
public boolean isConstructor() {
return false;
}
/**
* Whether this type is a nominal type (a named instance object or
* a named enum).
*/
public boolean isNominalType() {
return false;
}
/**
* Whether this type is the original constructor of a nominal type.
* Does not include structural constructors.
*/
public final boolean isNominalConstructor() {
if (isConstructor() || isInterface()) {
FunctionType fn = toMaybeFunctionType();
if (fn == null) {
return false;
}
// Programmer-defined constructors will have a link
// back to the original function in the source tree.
// Structural constructors will not.
if (fn.getSource() != null) {
return true;
}
// Native constructors are always nominal.
return fn.isNativeObjectType();
}
return false;
}
public boolean isNativeObjectType() {
return false;
}
/**
* Whether this type is an Instance object of some constructor.
* Does not necessarily mean this is an {@link InstanceObjectType}.
*/
public boolean isInstanceType() {
return false;
}
/**
* Whether this type is a {@link FunctionType} that is an interface or a named
* type that points to such a type.
*/
public boolean isInterface() {
return false;
}
/**
* Whether this type is a {@link FunctionType} that is an ordinary function (i.e. not a
* constructor, nominal interface, or record interface), or a named type that points to such a
* type.
*/
public boolean isOrdinaryFunction() {
return false;
}
@Override
public boolean equals(@Nullable Object jsType) {
return (jsType instanceof JSType) && isEquivalentTo((JSType) jsType);
}
/** Checks if two types are equivalent. */
public final boolean isEquivalentTo(@Nullable JSType that) {
return isEquivalentTo(that, false);
}
public final boolean isEquivalentTo(@Nullable JSType that, boolean isStructural) {
EqCache eqCache = isStructural ? EqCache.create() : EqCache.createWithoutStructuralTyping();
return checkEquivalenceHelper(that, EquivalenceMethod.IDENTITY, eqCache);
}
public static final boolean isEquivalent(@Nullable JSType typeA, @Nullable JSType typeB) {
return (typeA == null) ? (typeB == null) : typeA.isEquivalentTo(typeB);
}
/**
* Whether this type is meaningfully different from {@code that} type for
* the purposes of data flow analysis.
*
* This is a trickier check than pure equality, because it has to properly
* handle unknown types. See {@code EquivalenceMethod} for more info.
*
* @see <a href="http://www.youtube.com/watch?v=_RpSv3HjpEw">Unknown unknowns</a>
*/
public final boolean differsFrom(JSType that) {
return !checkEquivalenceHelper(that, EquivalenceMethod.DATA_FLOW, EqCache.create());
}
/**
* An equivalence visitor.
*/
@Deprecated
boolean checkEquivalenceHelper(final JSType that, EquivalenceMethod eqMethod) {
return checkEquivalenceHelper(
that,
eqMethod,
EqCache.create());
}
boolean checkEquivalenceHelper(
final @Nullable JSType that, EquivalenceMethod eqMethod, EqCache eqCache) {
if (that == null) {
return false;
} else if (areIdentical(this, that)) {
return true;
}
if (this.isNoResolvedType() && that.isNoResolvedType()) {
if (this.isNamedType() && that.isNamedType()) {
return Objects.equals(
this.toMaybeNamedType().getReferenceName(), //
that.toMaybeNamedType().getReferenceName());
} else {
return true;
}
}
boolean thisUnknown = isUnknownType();
boolean thatUnknown = that.isUnknownType();
if (thisUnknown || thatUnknown) {
if (eqMethod == EquivalenceMethod.INVARIANT) {
// If we're checking for invariance, the unknown type is invariant
// with everyone.
return true;
} else if (eqMethod == EquivalenceMethod.DATA_FLOW) {
// If we're checking data flow, then two types are the same if they're
// both unknown.
return thisUnknown && thatUnknown;
} else if (thisUnknown && thatUnknown &&
(isNominalType() ^ that.isNominalType())) {
// If they're both unknown, but one is a nominal type and the other
// is not, then we should fail out immediately. This ensures that
// we won't unbox the unknowns further down.
return false;
}
}
if (isUnionType() && that.isUnionType()) {
return toMaybeUnionType().checkUnionEquivalenceHelper(
that.toMaybeUnionType(), eqMethod, eqCache);
}
if (isFunctionType() && that.isFunctionType()) {
return toMaybeFunctionType().checkFunctionEquivalenceHelper(
that.toMaybeFunctionType(), eqMethod, eqCache);
}
if (!getTemplateTypeMap().checkEquivalenceHelper(
that.getTemplateTypeMap(), eqMethod, eqCache, SubtypingMode.NORMAL)) {
return false;
}
// Whether or not we use structural typing to compare object types is based on:
// 1. if eqCache.isStructuralTyping() is true, we always use structural typing
// 2. if we are comparing to anonymous record types (e.g. `{a: 3}`), always use structural types
// Ideally we would also use structural typing to compare anything declared @record, but
// that is harder to do with our current representation of types.
if (eqCache.shouldMatchStructurally(this, that)) {
return toMaybeObjectType()
.checkStructuralEquivalenceHelper(that.toMaybeObjectType(), eqMethod, eqCache);
}
if (isNominalType() && that.isNominalType()) {
// TODO(johnlenz): is this valid across scopes?
@Nullable String nameOfThis = deepestResolvedTypeNameOf(this.toObjectType());
@Nullable String nameOfThat = deepestResolvedTypeNameOf(that.toObjectType());
if ((nameOfThis == null) && (nameOfThat == null)) {
// These are two anonymous types that were masquerading as nominal, so don't compare names.
} else {
return Objects.equals(nameOfThis, nameOfThat);
}
}
if (isTemplateType() && that.isTemplateType()) {
// TemplateType are they same only if they are object identical,
// which we check at the start of this function.
return false;
}
// Unbox other proxies.
if (this instanceof ProxyObjectType) {
return ((ProxyObjectType) this)
.getReferencedTypeInternal().checkEquivalenceHelper(
that, eqMethod, eqCache);
}
if (that instanceof ProxyObjectType) {
return checkEquivalenceHelper(
((ProxyObjectType) that).getReferencedTypeInternal(),
eqMethod, eqCache);
}
// Relies on the fact that for the base {@link JSType}, only one
// instance of each sub-type will ever be created in a given registry, so
// there is no need to verify members. If the object pointers are not
// identical, then the type member must be different.
return false;
}
// Named types may be proxies of concrete types.
@Nullable
private String deepestResolvedTypeNameOf(ObjectType objType) {
if (!objType.isResolved() || !(objType instanceof ProxyObjectType)) {
return objType.getReferenceName();
}
ObjectType internal = ((ProxyObjectType) objType).getReferencedObjTypeInternal();
return (internal != null && internal.isNominalType())
? deepestResolvedTypeNameOf(internal)
: null;
}
/**
* Calculates a hash of the object as per {@link Object#hashCode()}.
*
* <p>This method is <em>unsafe</em> for multi-threaded use. The implementation mutates instance
* state to prevent recursion and therefore expects sole access.
*/
@Override
public final int hashCode() {
if (hashCodeInProgress) {
return -1; // Recursive base-case.
}
this.hashCodeInProgress = true;
int hashCode = recursionUnsafeHashCode();
this.hashCodeInProgress = false;
return hashCode;
}
/**
* Calculates {@code #hashCode()} with the assumption that it will never be called recursively.
*
* <p>To work correctly this method should only called under the following conditions:
*
* <ul>
* <li>by a subclass of {@link JSType};
* <li>within the body of an override;
* <li>when delegating to a superclass implementation.
* </ul>
*/
abstract int recursionUnsafeHashCode();
/**
* This predicate is used to test whether a given type can appear in a numeric context, such as an
* operand of a multiply operator.
*/
public boolean matchesNumberContext() {
return false;
}
/**
* This predicate is used to test whether a given type can appear in a
* {@code String} context, such as an operand of a string concat (+) operator.
*
* All types have at least the potential for converting to {@code String}.
* When we add externally defined types, such as a browser OM, we may choose
* to add types that do not automatically convert to {@code String}.
*/
public boolean matchesStringContext() {
return false;
}
/**
* This predicate is used to test whether a given type can appear in a
* {@code symbol} context such as property access.
*/
public boolean matchesSymbolContext() {
return false;
}
/**
* This predicate is used to test whether a given type can appear in an
* {@code Object} context, such as the expression in a with statement.
*
* Most types we will encounter, except notably {@code null}, have at least
* the potential for converting to {@code Object}. Host defined objects can
* get peculiar.
*/
public boolean matchesObjectContext() {
return false;
}
/**
* Coerces this type to an Object type, then gets the type of the property whose name is given.
*
* <p>Unlike {@link ObjectType#getPropertyType}, returns null if the property is not found.
*
* @return The property's type. {@code null} if the current type cannot have properties, or if the
* type is not found.
*/
@Nullable
public final JSType findPropertyType(String propertyName) {
@Nullable JSType propertyType = findPropertyTypeWithoutConsideringTemplateTypes(propertyName);
if (propertyType == null) {
return null;
}
// Do templatized type replacing logic here, and make this method final, to prevent a subclass
// from forgetting to replace template types
if (getTemplateTypeMap().isEmpty() || !propertyType.hasAnyTemplateTypes()) {
return propertyType;
}
TemplateTypeMap typeMap = getTemplateTypeMap();
TemplateTypeMapReplacer replacer = new TemplateTypeMapReplacer(registry, typeMap);
return propertyType.visit(replacer);
}
/**
* Looks up a property on this type, but without properly replacing any templates in the result.
*
* <p>Subclasses can override this if they need more complicated logic for property lookup than
* just autoboxing to an object.
*
* <p>This is only for use by {@code findPropertyType(JSType)}. Call that method instead if you
* need to lookup a property on a random JSType
*/
@ForOverride
@Nullable
protected JSType findPropertyTypeWithoutConsideringTemplateTypes(String propertyName) {
ObjectType autoboxObjType = ObjectType.cast(autoboxesTo());
if (autoboxObjType != null) {
return autoboxObjType.findPropertyType(propertyName);
}
return null;
}
/**
* This predicate is used to test whether a given type can be used as the
* 'function' in a function call.
*
* @return {@code true} if this type might be callable.
*/
public boolean canBeCalled() {
return false;
}
/**
* Tests whether values of {@code this} type can be safely assigned
* to values of {@code that} type.<p>
*
* The default implementation verifies that {@code this} is a subtype
* of {@code that}.<p>
*/
public final boolean canCastTo(JSType that) {
return this.visit(CAN_CAST_TO_VISITOR, that);
}
/**
* Turn a scalar type to the corresponding object type.
*
* @return the auto-boxed type or {@code null} if this type is not a scalar.
*/
public JSType autoboxesTo() {
return null;
}
public boolean isBoxableScalar() {
return autoboxesTo() != null;
}
// TODO(johnlenz): this method is only used for testing, consider removing this.
/**
* Turn an object type to its corresponding scalar type.
*
* @return the unboxed type or {@code null} if this type does not unbox.
*/
public JSType unboxesTo() {
return null;
}
/**
* Casts this to an ObjectType, or returns null if this is not an ObjectType.
* If this is a scalar type, it will *not* be converted to an object type.
* If you want to simulate JS autoboxing or dereferencing, you should use
* autoboxesTo() or dereference().
*/
public ObjectType toObjectType() {
return this instanceof ObjectType ? (ObjectType) this : null;
}
/**
* Dereferences a type for property access.
*
* Filters null/undefined and autoboxes the resulting type.
* Never returns null.
*/
public JSType autobox() {
JSType restricted = restrictByNotNullOrUndefined();
JSType autobox = restricted.autoboxesTo();
return autobox == null ? restricted : autobox;
}
/**
* Dereferences a type for property access.
*
* Filters null/undefined, autoboxes the resulting type, and returns it
* iff it's an object. If not an object, returns null.
*/
@Nullable
public final ObjectType dereference() {
return autobox().toObjectType();
}
/**
* Tests whether {@code this} and {@code that} are meaningfully
* comparable. By meaningfully, we mean compatible types that do not lead
* to step 22 of the definition of the Abstract Equality Comparison