-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
JSType.java
1846 lines (1634 loc) · 56.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
/*
*
* ***** 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.javascript.rhino.jstype.TernaryValue.UNKNOWN;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.javascript.rhino.ErrorReporter;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.TypeI;
import java.io.Serializable;
import java.util.Comparator;
import java.util.IdentityHashMap;
/**
* Represents JavaScript value types.<p>
*
* Types are split into two separate families: value types and object types.
*
* 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 TypeI, Serializable {
private static final long serialVersionUID = 1L;
private boolean resolved = false;
private JSType resolveResult = null;
protected TemplateTypeMap templateTypeMap;
private boolean inTemplatedCheckVisit = false;
private static final CanCastToVisitor CAN_CAST_TO_VISITOR =
new CanCastToVisitor();
private static final ImmutableSet<String> COVARIANT_TYPES =
ImmutableSet.of("Object", "IArrayLike", "Array");
/**
* Total ordering on types based on their textual representation.
* This is used to have a deterministic output of the toString
* method of the union type since this output is used in tests.
*/
static final Comparator<JSType> ALPHA = new Comparator<JSType>() {
@Override
public int compare(JSType t1, JSType t2) {
return t1.toString().compareTo(t2.toString());
}
};
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.
*/
@Override
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
*/
@Override
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();
}
/**
* Checks whether the property is present on the object.
* @param pname The property name.
*/
public boolean hasProperty(String pname) {
return false;
}
public boolean isNoType() {
return false;
}
public boolean isNoResolvedType() {
return false;
}
@Override
public final boolean isUnresolved() {
return isNoResolvedType();
}
@Override
public final boolean isUnresolvedOrResolvedUnknown() {
return isNoResolvedType() || isNamedType() && isUnknownType();
}
public boolean isNoObjectType() {
return false;
}
public final boolean isEmptyType() {
return isNoType() || isNoObjectType() || isNoResolvedType() ||
(registry.getNativeFunctionType(
JSTypeNative.LEAST_FUNCTION_TYPE) == this);
}
public boolean isNumberObjectType() {
return false;
}
@Override
public boolean isNumberValueType() {
return false;
}
/** Whether this is the prototype of a function. */
public boolean isFunctionPrototypeType() {
return false;
}
@Override
public boolean isPrototypeObject() {
return isFunctionPrototypeType();
}
public boolean isStringObjectType() {
return false;
}
boolean isTheObjectType() {
return false;
}
@Override
public boolean isStringValueType() {
return false;
}
/**
* Tests whether the type is a string (value or Object).
* @return <code>this <: (String, string)</code>
*/
public final boolean isString() {
return isSubtype(
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 isSubtype(
getNativeType(JSTypeNative.NUMBER_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;
}
@Override
public boolean isNullType() {
return false;
}
@Override
public boolean isVoidType() {
return false;
}
public boolean isAllType() {
return false;
}
@Override
public final boolean isTop() {
return isAllType();
}
@Override
public boolean isUnknownType() {
return false;
}
@Override
public final boolean isSomeUnknownType() {
// OTI's notion of isUnknownType already accounts for looseness (see override in ObjectType).
return isUnknownType();
}
public boolean isCheckedUnknownType() {
return false;
}
@Override
public final boolean isUnionType() {
return toMaybeUnionType() != null;
}
@Override
public boolean containsArray() {
// Check if this is itself an array
if (this.isArrayType()) {
return true;
}
TemplatizedType templatizedType = this.toMaybeTemplatizedType();
if (templatizedType != null && templatizedType.getReferencedType().isArrayType()) {
return true;
}
// Check if this is a union that contains an array
if (this.isUnionType()) {
JSType arrayType = registry.getNativeType(JSTypeNative.ARRAY_TYPE);
// use an indexed loop to avoid allocations
ImmutableList<JSType> alternatesList = this.toMaybeUnionType().getAlternatesList();
for (int i = 0; i < alternatesList.size(); i++) {
JSType alternate = alternatesList.get(i);
if (alternate.isSubtype(arrayType)) {
return true;
}
}
}
return false;
}
/**
* 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;
}
@Override
public final boolean isLiteralObject() {
if (this instanceof PrototypeObjectType) {
return ((PrototypeObjectType) this).isAnonymous();
}
return false;
}
@Override
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 this == registry.getNativeType(JSTypeNative.GLOBAL_THIS);
}
/** Returns true if toMaybeFunctionType returns a non-null FunctionType. */
@Override
public final boolean isFunctionType() {
return toMaybeFunctionType() != null;
}
/**
* Downcasts this to a FunctionType, or returns null if this is not
* a function.
*
* 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.
*
* This definition is somewhat arbitrary and axiomatic, but this is the
* definition that makes the most sense for the most callers.
*/
@Override
public FunctionType toMaybeFunctionType() {
return null;
}
/**
* Null-safe version of toMaybeFunctionType().
*/
public static FunctionType toMaybeFunctionType(JSType type) {
return type == null ? null : type.toMaybeFunctionType();
}
public final boolean isEnumElementType() {
return toMaybeEnumElementType() != null;
}
@Override
public final boolean isEnumElement() {
return isEnumElementType();
}
@Override
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;
}
public boolean isEnumType() {
return toMaybeEnumType() != null;
}
@Override
public final boolean isEnumObject() {
return isEnumType();
}
/**
* 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 boolean isLegacyNamedType() {
return isNamedType();
}
public NamedType toMaybeNamedType() {
return null;
}
public boolean isRecordType() {
return toMaybeRecordType() != null;
}
@Override
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 isGeneric() {
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;
}
@Override
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;
}
/**
* 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;
}
@Override
public final boolean isObjectType() {
return isObject();
}
@Override
public final boolean isInstanceofObject() {
// Some type whose class is Object
if (this instanceof InstanceObjectType) {
InstanceObjectType iObj = (InstanceObjectType) this;
return iObj.isNativeObjectType() && "Object".equals(iObj.getReferenceName());
}
return isRecordType() || isLiteralObject();
}
/**
* Whether this type is a {@link FunctionType} that is a constructor or a
* named type that points to such a type.
*/
@Override
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;
}
/**
* 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.
*/
@Override
public boolean isInterface() {
return false;
}
/**
* Whether this type is a {@link FunctionType} that is an ordinary function or
* a named type that points to such a type.
*/
public boolean isOrdinaryFunction() {
return false;
}
/**
* Checks if two types are equivalent.
*/
@Override
public final boolean isEquivalentTo(TypeI that) {
return checkEquivalenceHelper((JSType) that, EquivalenceMethod.IDENTITY);
}
public final boolean isEquivalentTo(TypeI that, boolean isStructural) {
EqCache eqCache = isStructural ? EqCache.create()
: EqCache.createWithoutStructuralTyping();
return checkEquivalenceHelper((JSType) that,
EquivalenceMethod.IDENTITY, eqCache);
}
/**
* 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);
}
/**
* An equivalence visitor.
*/
boolean checkEquivalenceHelper(
final JSType that, EquivalenceMethod eqMethod) {
return checkEquivalenceHelper(that, eqMethod, EqCache.create());
}
boolean checkEquivalenceHelper(final JSType that, EquivalenceMethod eqMethod,
EqCache eqCache) {
if (this == that) {
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;
}
if (eqCache.isStructuralTyping() && this.isStructuralType() && that.isStructuralType()) {
return toMaybeObjectType()
.checkStructuralEquivalenceHelper(that.toMaybeObjectType(), eqMethod, eqCache);
}
if (isNominalType() && that.isNominalType()) {
// TODO(johnlenz): is this valid across scopes?
return getConcreteNominalTypeName(this.toObjectType())
.equals(getConcreteNominalTypeName(that.toObjectType()));
}
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.
private String getConcreteNominalTypeName(ObjectType objType) {
if (objType instanceof ProxyObjectType) {
ObjectType internal = ((ProxyObjectType) objType)
.getReferencedObjTypeInternal();
if (internal != null && internal.isNominalType()) {
return getConcreteNominalTypeName(internal);
}
}
return objType.getReferenceName();
}
public static boolean isEquivalent(JSType typeA, JSType typeB) {
return (typeA == null || typeB == null)
? typeA == typeB : typeA.isEquivalentTo(typeB);
}
@Override
public boolean equals(Object jsType) {
return (jsType instanceof JSType) && isEquivalentTo((JSType) jsType);
}
@Override
public abstract int hashCode();
/**
* This predicate is used to test whether a given type can appear in a
* 'Int32' context. This context includes, for example, the operands of a
* bitwise or operator. Since we do not currently support integer types,
* this is a synonym for {@code Number}.
*/
public final boolean matchesInt32Context() {
return matchesNumberContext();
}
/**
* This predicate is used to test whether a given type can appear in a
* 'Uint32' context. This context includes the right-hand operand of a shift
* operator.
*/
public final boolean matchesUint32Context() {
return matchesNumberContext();
}
/**
* 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 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.
*
* 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.
*/
public JSType findPropertyType(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 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;
}
@Override
public boolean isBoxableScalar() {
return autoboxesTo() != null;
}
/**
* 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;
}
/**
* Dereference a type for property access.
*
* Filters null/undefined and autoboxes the resulting type.
* Never returns null.
*/
@Override
public JSType autobox() {
JSType restricted = restrictByNotNullOrUndefined();
JSType autobox = restricted.autoboxesTo();
return autobox == null ? restricted : autobox;
}
/**
* Dereference a type for property access.
*
* Filters null/undefined, autoboxes the resulting type, and returns it
* iff it's an object.
*/
public final ObjectType dereference() {
return autobox().toObjectType();
}
@Override
public final ObjectType autoboxAndGetObject() {
return dereference();
}
/**
* 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
* Algorithm (11.9.3, page 55–56) of the ECMA-262 specification.<p>
*/
public final boolean canTestForEqualityWith(JSType that) {
return testForEquality(that).equals(UNKNOWN);
}
/**
* Compares {@code this} and {@code that}.
* @return <ul>
* <li>{@link TernaryValue#TRUE} if the comparison of values of
* {@code this} type and {@code that} always succeed (such as
* {@code undefined} compared to {@code null})</li>
* <li>{@link TernaryValue#FALSE} if the comparison of values of
* {@code this} type and {@code that} always fails (such as
* {@code undefined} compared to {@code number})</li>
* <li>{@link TernaryValue#UNKNOWN} if the comparison can succeed or
* fail depending on the concrete values</li>
* </ul>
*/
public TernaryValue testForEquality(JSType that) {
return testForEqualityHelper(this, that);
}
TernaryValue testForEqualityHelper(JSType aType, JSType bType) {
if (bType.isAllType() || bType.isUnknownType() ||
bType.isNoResolvedType() ||
aType.isAllType() || aType.isUnknownType() ||
aType.isNoResolvedType()) {
return UNKNOWN;
}
boolean aIsEmpty = aType.isEmptyType();
boolean bIsEmpty = bType.isEmptyType();
if (aIsEmpty || bIsEmpty) {
if (aIsEmpty && bIsEmpty) {
return TernaryValue.TRUE;
} else {
return UNKNOWN;
}
}
if (aType.isFunctionType() || bType.isFunctionType()) {
JSType otherType = aType.isFunctionType() ? bType : aType;
// In theory, functions are comparable to anything except
// null/undefined. For example, on FF3:
// function() {} == 'function () {\n}'
// In practice, how a function serializes to a string is
// implementation-dependent, so it does not really make sense to test
// for equality with a string.
JSType meet = otherType.getGreatestSubtype(
getNativeType(JSTypeNative.OBJECT_TYPE));
if (meet.isNoType() || meet.isNoObjectType()) {
return TernaryValue.FALSE;
} else {
return TernaryValue.UNKNOWN;