-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
JSTypeRegistry.java
2235 lines (1992 loc) · 80.5 KB
/
JSTypeRegistry.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.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.javascript.rhino.jstype.JSTypeNative.ALL_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NO_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.UNKNOWN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.VOID_TYPE;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import com.google.javascript.rhino.ErrorReporter;
import com.google.javascript.rhino.FunctionTypeI;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSTypeExpression;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.ObjectTypeI;
import com.google.javascript.rhino.SimpleErrorReporter;
import com.google.javascript.rhino.StaticScope;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.TypeI;
import com.google.javascript.rhino.TypeIEnv;
import com.google.javascript.rhino.TypeIRegistry;
import com.google.javascript.rhino.jstype.FunctionType.Kind;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* The type registry is used to resolve named types.
*
* <p>This class is not thread-safe.
*
*/
public class JSTypeRegistry implements TypeIRegistry {
private static final long serialVersionUID = 1L;
/**
* The template variable corresponding to the KEY type in {@code IObject<KEY, VALUE>}
* (plus the builtin Javascript Object).
*/
private TemplateType iObjectIndexTemplateKey;
/**
* The template variable corresponding to the VALUE type in {@code IObject<KEY, VALUE>}
* (plus the builtin Javascript Object).
*/
private TemplateType iObjectElementTemplateKey;
private static final String I_OBJECT_ELEMENT_TEMPLATE = "IObject#VALUE";
/** The template variable corresponding to the VALUE type in {@code Iterable<VALUE>} */
private TemplateType iterableTemplate;
/**
* The template variable in {@code Array<T>}
*/
private TemplateType arrayElementTemplateKey;
@Deprecated
public static final String OBJECT_ELEMENT_TEMPLATE = I_OBJECT_ELEMENT_TEMPLATE;
/**
* The UnionTypeBuilder caps the maximum number of alternate types it
* remembers and then defaults to "?" (unknown type). By default this max
* is 20, but it's very easy for the same property to appear on more than 20
* types. Use larger unions for property checking. 3000 was picked
* semi-randomly for use by the Google+ FE project.
*/
private static final int PROPERTY_CHECKING_UNION_SIZE = 3000;
// TODO(user): An instance of this class should be used during
// compilation. We also want to make all types' constructors package private
// and force usage of this registry instead. This will allow us to evolve the
// types without being tied by an open API.
private final transient ErrorReporter reporter;
// We use an Array instead of an immutable list because this lookup needs
// to be very fast. When it was an immutable list, we were spending 5% of
// CPU time on bounds checking inside get().
private final JSType[] nativeTypes;
private final Map<String, JSType> namesToTypes;
// NOTE(nicksantos): This is a terrible terrible hack. When type expressions
// are evaluated, we need to be able to decide whether that type name
// resolves to a nullable type or a non-nullable type. Object types are
// nullable, but enum types are not.
//
// Notice that it's not good enough to just declare enum types sooner.
// For example, if we have
// /** @enum {MyObject} */ var MyEnum = ...;
// we won't be to declare "MyEnum" without evaluating the expression
// {MyObject}, and following those dependencies starts to lead us into
// undecidable territory. Instead, we "pre-declare" enum types and typedefs,
// so that the expression resolver can decide whether a given name is
// nullable or not.
private final Set<String> nonNullableTypeNames = new LinkedHashSet<>();
// Types that have been "forward-declared."
// If these types are not declared anywhere in the binary, we shouldn't
// try to type-check them at all.
private final transient Set<String> forwardDeclaredTypes;
// A map of properties to the types on which those properties have been
// declared.
private final Map<String, UnionTypeBuilder> typesIndexedByProperty =
new HashMap<>();
private JSType sentinelObjectLiteral;
// To avoid blowing up the size of typesIndexedByProperty, we use the sentinel object
// literal instead of registering arbitrarily many types.
// But because of the way unions are constructed, some properties of record types in unions
// are getting dropped and cause spurious "non-existent property" warnings.
// The next two fields avoid the warnings. The first field contains property names of records
// that participate in unions, and have caused properties to be dropped.
// The second field contains the names of the dropped properties. When checking
// canPropertyBeDefined, if the type has a property in propertiesOfSupertypesInUnions, we
// consider it to possibly have any property in droppedPropertiesOfUnions. This is a loose
// check, but we restrict it to records that may be present in unions, and it allows us to
// keep typesIndexedByProperty small.
private final Set<String> propertiesOfSupertypesInUnions = new HashSet<>();
private final Set<String> droppedPropertiesOfUnions = new HashSet<>();
// A map of properties to each reference type on which those
// properties have been declared. Each type has a unique name used
// for de-duping.
private transient Map<String, Map<String, ObjectType>> eachRefTypeIndexedByProperty =
new LinkedHashMap<>();
// A map of properties to the greatest subtype on which those properties have
// been declared. This is filled lazily from the types declared in
// typesIndexedByProperty.
private final Map<String, JSType> greatestSubtypeByProperty =
new HashMap<>();
// A map from interface name to types that implement it.
private transient Multimap<String, FunctionTypeI> interfaceToImplementors =
LinkedHashMultimap.create();
// All the unresolved named types.
private final Multimap<StaticTypedScope<JSType>, NamedType> unresolvedNamedTypes =
ArrayListMultimap.create();
// All the resolved named types.
private final Multimap<StaticTypedScope<JSType>, NamedType> resolvedNamedTypes =
ArrayListMultimap.create();
// The template type name.
private final Map<String, TemplateType> templateTypes = new HashMap<>();
// A single empty TemplateTypeMap, which can be safely reused in cases where
// there are no template types.
private final TemplateTypeMap emptyTemplateTypeMap;
public JSTypeRegistry(ErrorReporter reporter) {
this(reporter, ImmutableSet.<String>of());
}
/** Constructs a new type registry populated with the built-in types. */
public JSTypeRegistry(ErrorReporter reporter, Set<String> forwardDeclaredTypes) {
this.reporter = reporter;
this.forwardDeclaredTypes = forwardDeclaredTypes;
this.emptyTemplateTypeMap = new TemplateTypeMap(
this, ImmutableList.<TemplateType>of(), ImmutableList.<JSType>of());
nativeTypes = new JSType[JSTypeNative.values().length];
namesToTypes = new HashMap<>();
resetForTypeCheck();
}
private JSType getSentinelObjectLiteral() {
if (this.sentinelObjectLiteral == null) {
this.sentinelObjectLiteral = createAnonymousObjectType(null);
}
return this.sentinelObjectLiteral;
}
/**
* @return The template variable corresponding to the property value type for
* Javascript Objects and Arrays.
*/
public TemplateType getObjectElementKey() {
return this.iObjectElementTemplateKey;
}
/**
* @return The template variable corresponding to the
* property key type of the built-in Javascript object.
*/
public TemplateType getObjectIndexKey() {
checkNotNull(iObjectIndexTemplateKey);
return this.iObjectIndexTemplateKey;
}
/**
* Check if a function declaration is one of the templated builitin contructor/interfaces,
* namely one of IObject, IArrayLike, or Array
* @param fnName the function's name
* @param info the JSDoc from the function declaration
*/
public boolean isTemplatedBuiltin(String fnName, JSDocInfo info) {
ImmutableList<TemplateType> requiredTemplateTypes = getTemplateTypesOfBuiltin(fnName);
ImmutableList<String> infoTemplateTypeNames = info.getTemplateTypeNames();
return requiredTemplateTypes != null
&& infoTemplateTypeNames.size() == requiredTemplateTypes.size();
}
/**
* @return return an immutable list of template types of the given builtin.
*/
public ImmutableList<TemplateType> getTemplateTypesOfBuiltin(String fnName) {
switch (fnName) {
case "IObject":
return ImmutableList.of(iObjectIndexTemplateKey, iObjectElementTemplateKey);
case "Array":
return ImmutableList.of(arrayElementTemplateKey);
case "Iterable":
return ImmutableList.of(iterableTemplate);
default:
return null;
}
}
public ErrorReporter getErrorReporter() {
return reporter;
}
/**
* Reset to run the TypeCheck pass.
*/
public void resetForTypeCheck() {
typesIndexedByProperty.clear();
eachRefTypeIndexedByProperty.clear();
initializeBuiltInTypes();
namesToTypes.clear();
initializeRegistry();
}
private void initializeBuiltInTypes() {
// These locals shouldn't be all caps.
BooleanType BOOLEAN_TYPE = new BooleanType(this);
registerNativeType(JSTypeNative.BOOLEAN_TYPE, BOOLEAN_TYPE);
NullType NULL_TYPE = new NullType(this);
registerNativeType(JSTypeNative.NULL_TYPE, NULL_TYPE);
NumberType NUMBER_TYPE = new NumberType(this);
registerNativeType(JSTypeNative.NUMBER_TYPE, NUMBER_TYPE);
StringType STRING_TYPE = new StringType(this);
registerNativeType(JSTypeNative.STRING_TYPE, STRING_TYPE);
SymbolType SYMBOL_TYPE = new SymbolType(this);
registerNativeType(JSTypeNative.SYMBOL_TYPE, SYMBOL_TYPE);
UnknownType UNKNOWN_TYPE = new UnknownType(this, false);
registerNativeType(JSTypeNative.UNKNOWN_TYPE, UNKNOWN_TYPE);
UnknownType checkedUnknownType = new UnknownType(this, true);
registerNativeType(
JSTypeNative.CHECKED_UNKNOWN_TYPE, checkedUnknownType);
VoidType VOID_TYPE = new VoidType(this);
registerNativeType(JSTypeNative.VOID_TYPE, VOID_TYPE);
AllType ALL_TYPE = new AllType(this);
registerNativeType(JSTypeNative.ALL_TYPE, ALL_TYPE);
// Template Types
iObjectIndexTemplateKey = new TemplateType(this, "IObject#KEY1");
iObjectElementTemplateKey = new TemplateType(this, I_OBJECT_ELEMENT_TEMPLATE);
arrayElementTemplateKey = new TemplateType(this, "T");
iterableTemplate = new TemplateType(this, "VALUE");
// Top Level Prototype (the One)
// The initializations of TOP_LEVEL_PROTOTYPE and OBJECT_FUNCTION_TYPE
// use each other's results, so at least one of them will get null
// instead of an actual type; however, this seems to be benign.
PrototypeObjectType TOP_LEVEL_PROTOTYPE =
new PrototypeObjectType(this, null, null, true, null);
registerNativeType(JSTypeNative.TOP_LEVEL_PROTOTYPE, TOP_LEVEL_PROTOTYPE);
// Object
FunctionType OBJECT_FUNCTION_TYPE =
new FunctionType(
this,
"Object",
null,
createArrowType(createOptionalParameters(ALL_TYPE), null),
null,
createTemplateTypeMap(
ImmutableList.of(iObjectIndexTemplateKey, iObjectElementTemplateKey), null),
true,
true,
false);
OBJECT_FUNCTION_TYPE.getInternalArrowType().returnType =
OBJECT_FUNCTION_TYPE.getInstanceType();
OBJECT_FUNCTION_TYPE.setPrototype(TOP_LEVEL_PROTOTYPE, null);
registerNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE, OBJECT_FUNCTION_TYPE);
ObjectType OBJECT_TYPE = OBJECT_FUNCTION_TYPE.getInstanceType();
registerNativeType(JSTypeNative.OBJECT_TYPE, OBJECT_TYPE);
ObjectType OBJECT_PROTOTYPE = OBJECT_FUNCTION_TYPE.getPrototype();
registerNativeType(JSTypeNative.OBJECT_PROTOTYPE, OBJECT_PROTOTYPE);
// Function
FunctionType FUNCTION_FUNCTION_TYPE =
new FunctionType(
this,
"Function",
null,
createArrowType(createParametersWithVarArgs(ALL_TYPE), UNKNOWN_TYPE),
null,
null,
true,
true,
false);
FUNCTION_FUNCTION_TYPE.setPrototypeBasedOn(OBJECT_TYPE);
registerNativeType(
JSTypeNative.FUNCTION_FUNCTION_TYPE, FUNCTION_FUNCTION_TYPE);
ObjectType FUNCTION_PROTOTYPE = FUNCTION_FUNCTION_TYPE.getPrototype();
registerNativeType(JSTypeNative.FUNCTION_PROTOTYPE, FUNCTION_PROTOTYPE);
NoType NO_TYPE = new NoType(this);
registerNativeType(JSTypeNative.NO_TYPE, NO_TYPE);
NoObjectType NO_OBJECT_TYPE = new NoObjectType(this);
registerNativeType(JSTypeNative.NO_OBJECT_TYPE, NO_OBJECT_TYPE);
NoObjectType NO_RESOLVED_TYPE = new NoResolvedType(this);
registerNativeType(JSTypeNative.NO_RESOLVED_TYPE, NO_RESOLVED_TYPE);
// Array
FunctionType ARRAY_FUNCTION_TYPE =
new FunctionType(
this,
"Array",
null,
createArrowType(createParametersWithVarArgs(ALL_TYPE), null),
null,
createTemplateTypeMap(ImmutableList.of(arrayElementTemplateKey), null)
.extend(
createTemplateTypeMap(
ImmutableList.of(iObjectElementTemplateKey),
ImmutableList.<JSType>of(arrayElementTemplateKey))),
true,
true,
false);
ARRAY_FUNCTION_TYPE.getInternalArrowType().returnType =
ARRAY_FUNCTION_TYPE.getInstanceType();
ARRAY_FUNCTION_TYPE.getPrototype(); // Force initialization
registerNativeType(JSTypeNative.ARRAY_FUNCTION_TYPE, ARRAY_FUNCTION_TYPE);
ObjectType ARRAY_TYPE = ARRAY_FUNCTION_TYPE.getInstanceType();
registerNativeType(JSTypeNative.ARRAY_TYPE, ARRAY_TYPE);
FunctionType iterableFunctionType =
new FunctionType(
this,
"Iterable",
null,
createArrowType(),
null,
createTemplateTypeMap(ImmutableList.of(iterableTemplate), null),
Kind.INTERFACE,
true,
false);
registerNativeType(JSTypeNative.ITERABLE_FUNCTION_TYPE, iterableFunctionType);
registerNativeType(JSTypeNative.ITERABLE_TYPE, iterableFunctionType.getInstanceType());
// Boolean
FunctionType BOOLEAN_OBJECT_FUNCTION_TYPE =
new FunctionType(
this,
"Boolean",
null,
createArrowType(createOptionalParameters(ALL_TYPE), BOOLEAN_TYPE),
null,
null,
true,
true,
false);
BOOLEAN_OBJECT_FUNCTION_TYPE.getPrototype(); // Force initialization
registerNativeType(
JSTypeNative.BOOLEAN_OBJECT_FUNCTION_TYPE,
BOOLEAN_OBJECT_FUNCTION_TYPE);
ObjectType BOOLEAN_OBJECT_TYPE =
BOOLEAN_OBJECT_FUNCTION_TYPE.getInstanceType();
registerNativeType(JSTypeNative.BOOLEAN_OBJECT_TYPE, BOOLEAN_OBJECT_TYPE);
// Date
FunctionType DATE_FUNCTION_TYPE =
new FunctionType(
this,
"Date",
null,
createArrowType(
createOptionalParameters(
UNKNOWN_TYPE,
UNKNOWN_TYPE,
UNKNOWN_TYPE,
UNKNOWN_TYPE,
UNKNOWN_TYPE,
UNKNOWN_TYPE,
UNKNOWN_TYPE),
STRING_TYPE),
null,
null,
true,
true,
false);
DATE_FUNCTION_TYPE.getPrototype(); // Force initialization
registerNativeType(JSTypeNative.DATE_FUNCTION_TYPE, DATE_FUNCTION_TYPE);
ObjectType DATE_TYPE = DATE_FUNCTION_TYPE.getInstanceType();
registerNativeType(JSTypeNative.DATE_TYPE, DATE_TYPE);
// Error
FunctionType ERROR_FUNCTION_TYPE = new ErrorFunctionType(this, "Error");
registerNativeType(JSTypeNative.ERROR_FUNCTION_TYPE, ERROR_FUNCTION_TYPE);
ObjectType ERROR_TYPE = ERROR_FUNCTION_TYPE.getInstanceType();
registerNativeType(JSTypeNative.ERROR_TYPE, ERROR_TYPE);
// EvalError
FunctionType EVAL_ERROR_FUNCTION_TYPE =
new ErrorFunctionType(this, "EvalError");
EVAL_ERROR_FUNCTION_TYPE.setPrototypeBasedOn(ERROR_TYPE);
registerNativeType(
JSTypeNative.EVAL_ERROR_FUNCTION_TYPE, EVAL_ERROR_FUNCTION_TYPE);
ObjectType EVAL_ERROR_TYPE = EVAL_ERROR_FUNCTION_TYPE.getInstanceType();
registerNativeType(JSTypeNative.EVAL_ERROR_TYPE, EVAL_ERROR_TYPE);
// RangeError
FunctionType RANGE_ERROR_FUNCTION_TYPE =
new ErrorFunctionType(this, "RangeError");
RANGE_ERROR_FUNCTION_TYPE.setPrototypeBasedOn(ERROR_TYPE);
registerNativeType(
JSTypeNative.RANGE_ERROR_FUNCTION_TYPE, RANGE_ERROR_FUNCTION_TYPE);
ObjectType RANGE_ERROR_TYPE = RANGE_ERROR_FUNCTION_TYPE.getInstanceType();
registerNativeType(JSTypeNative.RANGE_ERROR_TYPE, RANGE_ERROR_TYPE);
// ReferenceError
FunctionType REFERENCE_ERROR_FUNCTION_TYPE =
new ErrorFunctionType(this, "ReferenceError");
REFERENCE_ERROR_FUNCTION_TYPE.setPrototypeBasedOn(ERROR_TYPE);
registerNativeType(
JSTypeNative.REFERENCE_ERROR_FUNCTION_TYPE,
REFERENCE_ERROR_FUNCTION_TYPE);
ObjectType REFERENCE_ERROR_TYPE =
REFERENCE_ERROR_FUNCTION_TYPE.getInstanceType();
registerNativeType(JSTypeNative.REFERENCE_ERROR_TYPE, REFERENCE_ERROR_TYPE);
// SyntaxError
FunctionType SYNTAX_ERROR_FUNCTION_TYPE =
new ErrorFunctionType(this, "SyntaxError");
SYNTAX_ERROR_FUNCTION_TYPE.setPrototypeBasedOn(ERROR_TYPE);
registerNativeType(
JSTypeNative.SYNTAX_ERROR_FUNCTION_TYPE, SYNTAX_ERROR_FUNCTION_TYPE);
ObjectType SYNTAX_ERROR_TYPE = SYNTAX_ERROR_FUNCTION_TYPE.getInstanceType();
registerNativeType(JSTypeNative.SYNTAX_ERROR_TYPE, SYNTAX_ERROR_TYPE);
// TypeError
FunctionType TYPE_ERROR_FUNCTION_TYPE =
new ErrorFunctionType(this, "TypeError");
TYPE_ERROR_FUNCTION_TYPE.setPrototypeBasedOn(ERROR_TYPE);
registerNativeType(
JSTypeNative.TYPE_ERROR_FUNCTION_TYPE, TYPE_ERROR_FUNCTION_TYPE);
ObjectType TYPE_ERROR_TYPE = TYPE_ERROR_FUNCTION_TYPE.getInstanceType();
registerNativeType(JSTypeNative.TYPE_ERROR_TYPE, TYPE_ERROR_TYPE);
// URIError
FunctionType URI_ERROR_FUNCTION_TYPE =
new ErrorFunctionType(this, "URIError");
URI_ERROR_FUNCTION_TYPE.setPrototypeBasedOn(ERROR_TYPE);
registerNativeType(
JSTypeNative.URI_ERROR_FUNCTION_TYPE, URI_ERROR_FUNCTION_TYPE);
ObjectType URI_ERROR_TYPE = URI_ERROR_FUNCTION_TYPE.getInstanceType();
registerNativeType(JSTypeNative.URI_ERROR_TYPE, URI_ERROR_TYPE);
// Number
FunctionType NUMBER_OBJECT_FUNCTION_TYPE =
new FunctionType(
this,
"Number",
null,
createArrowType(createOptionalParameters(ALL_TYPE), NUMBER_TYPE),
null,
null,
true,
true,
false);
NUMBER_OBJECT_FUNCTION_TYPE.getPrototype(); // Force initialization
registerNativeType(
JSTypeNative.NUMBER_OBJECT_FUNCTION_TYPE, NUMBER_OBJECT_FUNCTION_TYPE);
ObjectType NUMBER_OBJECT_TYPE =
NUMBER_OBJECT_FUNCTION_TYPE.getInstanceType();
registerNativeType(JSTypeNative.NUMBER_OBJECT_TYPE, NUMBER_OBJECT_TYPE);
// RegExp
FunctionType REGEXP_FUNCTION_TYPE =
new FunctionType(
this,
"RegExp",
null,
createArrowType(createOptionalParameters(ALL_TYPE, ALL_TYPE)),
null,
null,
true,
true,
false);
REGEXP_FUNCTION_TYPE.getInternalArrowType().returnType =
REGEXP_FUNCTION_TYPE.getInstanceType();
REGEXP_FUNCTION_TYPE.getPrototype(); // Force initialization
registerNativeType(JSTypeNative.REGEXP_FUNCTION_TYPE, REGEXP_FUNCTION_TYPE);
ObjectType REGEXP_TYPE = REGEXP_FUNCTION_TYPE.getInstanceType();
registerNativeType(JSTypeNative.REGEXP_TYPE, REGEXP_TYPE);
// String
FunctionType STRING_OBJECT_FUNCTION_TYPE =
new FunctionType(
this,
"String",
null,
createArrowType(createOptionalParameters(ALL_TYPE), STRING_TYPE),
null,
null,
true,
true,
false);
STRING_OBJECT_FUNCTION_TYPE.getPrototype(); // Force initialization
registerNativeType(
JSTypeNative.STRING_OBJECT_FUNCTION_TYPE, STRING_OBJECT_FUNCTION_TYPE);
ObjectType STRING_OBJECT_TYPE =
STRING_OBJECT_FUNCTION_TYPE.getInstanceType();
registerNativeType(
JSTypeNative.STRING_OBJECT_TYPE, STRING_OBJECT_TYPE);
// Symbol
// NOTE: While "Symbol" is a class, with an instance type and prototype
// it is illegal to call "new Symbol". This is checked to in the
// type checker.
FunctionType SYMBOL_OBJECT_FUNCTION_TYPE =
new FunctionType(
this,
"Symbol",
null,
createArrowType(createOptionalParameters(ALL_TYPE), SYMBOL_TYPE),
null,
null,
true,
true,
false);
SYMBOL_OBJECT_FUNCTION_TYPE.getPrototype(); // Force initialization
registerNativeType(
JSTypeNative.SYMBOL_OBJECT_FUNCTION_TYPE, SYMBOL_OBJECT_FUNCTION_TYPE);
ObjectType SYMBOL_OBJECT_TYPE =
SYMBOL_OBJECT_FUNCTION_TYPE.getInstanceType();
registerNativeType(
JSTypeNative.SYMBOL_OBJECT_TYPE, SYMBOL_OBJECT_TYPE);
// (null,void)
JSType NULL_VOID =
createUnionType(NULL_TYPE, VOID_TYPE);
registerNativeType(JSTypeNative.NULL_VOID, NULL_VOID);
// (Object,symbol)
JSType OBJECT_SYMBOL = createUnionType(OBJECT_TYPE, SYMBOL_TYPE);
registerNativeType(JSTypeNative.OBJECT_SYMBOL, OBJECT_SYMBOL);
// (Object,string,number)
JSType OBJECT_NUMBER_STRING =
createUnionType(OBJECT_TYPE, NUMBER_TYPE, STRING_TYPE);
registerNativeType(JSTypeNative.OBJECT_NUMBER_STRING, OBJECT_NUMBER_STRING);
// (Object,string,number,boolean)
JSType OBJECT_NUMBER_STRING_BOOLEAN =
createUnionType(OBJECT_TYPE, NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE);
registerNativeType(JSTypeNative.OBJECT_NUMBER_STRING_BOOLEAN,
OBJECT_NUMBER_STRING_BOOLEAN);
// (Object,string,number,boolean,symbol)
JSType OBJECT_NUMBER_STRING_BOOLEAN_SYMBOL =
createUnionType(OBJECT_TYPE, NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE, SYMBOL_TYPE);
registerNativeType(JSTypeNative.OBJECT_NUMBER_STRING_BOOLEAN_SYMBOL,
OBJECT_NUMBER_STRING_BOOLEAN_SYMBOL);
// (string,number,boolean)
JSType NUMBER_STRING_BOOLEAN =
createUnionType(NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE);
registerNativeType(JSTypeNative.NUMBER_STRING_BOOLEAN,
NUMBER_STRING_BOOLEAN);
// (string,number,boolean,symbol)
JSType NUMBER_STRING_BOOLEAN_SYMBOL =
createUnionType(NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE, SYMBOL_TYPE);
registerNativeType(JSTypeNative.NUMBER_STRING_BOOLEAN_SYMBOL,
NUMBER_STRING_BOOLEAN_SYMBOL);
// (number,symbol)
JSType NUMBER_SYMBOL = createUnionType(NUMBER_TYPE, SYMBOL_TYPE);
registerNativeType(JSTypeNative.NUMBER_SYMBOL, NUMBER_SYMBOL);
// (string,symbol)
JSType STRING_SYMBOL = createUnionType(STRING_TYPE, SYMBOL_TYPE);
registerNativeType(JSTypeNative.STRING_SYMBOL, STRING_SYMBOL);
// (string,number)
JSType NUMBER_STRING = createUnionType(NUMBER_TYPE, STRING_TYPE);
registerNativeType(JSTypeNative.NUMBER_STRING, NUMBER_STRING);
// (string,number,symbol)
JSType NUMBER_STRING_SYMBOL = createUnionType(NUMBER_TYPE, STRING_TYPE, SYMBOL_TYPE);
registerNativeType(JSTypeNative.NUMBER_STRING_SYMBOL, NUMBER_STRING_SYMBOL);
// Native object properties are filled in by externs...
// (String, string)
JSType STRING_VALUE_OR_OBJECT_TYPE =
createUnionType(STRING_OBJECT_TYPE, STRING_TYPE);
registerNativeType(
JSTypeNative.STRING_VALUE_OR_OBJECT_TYPE, STRING_VALUE_OR_OBJECT_TYPE);
// (Number, number)
JSType NUMBER_VALUE_OR_OBJECT_TYPE =
createUnionType(NUMBER_OBJECT_TYPE, NUMBER_TYPE);
registerNativeType(
JSTypeNative.NUMBER_VALUE_OR_OBJECT_TYPE, NUMBER_VALUE_OR_OBJECT_TYPE);
// (Symbol, symbol)
JSType SYMBOL_VALUE_OR_OBJECT_TYPE =
createUnionType(SYMBOL_OBJECT_TYPE, SYMBOL_TYPE);
registerNativeType(
JSTypeNative.SYMBOL_VALUE_OR_OBJECT_TYPE, SYMBOL_VALUE_OR_OBJECT_TYPE);
// unknown function type, i.e. (?...) -> ?
FunctionType U2U_FUNCTION_TYPE =
createFunctionTypeWithVarArgs(UNKNOWN_TYPE, UNKNOWN_TYPE);
registerNativeType(JSTypeNative.U2U_FUNCTION_TYPE, U2U_FUNCTION_TYPE);
// unknown constructor type, i.e. (?...) -> ? with the Unknown type
// as instance type
FunctionType U2U_CONSTRUCTOR_TYPE =
// This is equivalent to
// createConstructorType(UNKNOWN_TYPE, true, UNKNOWN_TYPE), but,
// in addition, overrides getInstanceType() to return the NoObject type
// instead of a new anonymous object.
new FunctionType(
this,
"Function",
null,
createArrowType(createParametersWithVarArgs(UNKNOWN_TYPE), UNKNOWN_TYPE),
UNKNOWN_TYPE,
null,
true,
true,
false) {
private static final long serialVersionUID = 1L;
@Override
public FunctionType getConstructor() {
return registry.getNativeFunctionType(JSTypeNative.FUNCTION_FUNCTION_TYPE);
}
};
// The U2U_CONSTRUCTOR is weird, because it's the supertype of its
// own constructor.
registerNativeType(JSTypeNative.U2U_CONSTRUCTOR_TYPE, U2U_CONSTRUCTOR_TYPE);
registerNativeType(
JSTypeNative.FUNCTION_INSTANCE_TYPE, U2U_CONSTRUCTOR_TYPE);
FUNCTION_FUNCTION_TYPE.setInstanceType(U2U_CONSTRUCTOR_TYPE);
U2U_CONSTRUCTOR_TYPE.setImplicitPrototype(FUNCTION_PROTOTYPE);
// least function type, i.e. (All...) -> NoType
FunctionType LEAST_FUNCTION_TYPE =
createNativeFunctionTypeWithVarArgs(NO_TYPE, ALL_TYPE);
registerNativeType(JSTypeNative.LEAST_FUNCTION_TYPE, LEAST_FUNCTION_TYPE);
// the 'this' object in the global scope
FunctionType GLOBAL_THIS_CTOR =
new FunctionType(
this,
"global this",
null,
createArrowType(createParameters(false, ALL_TYPE), NUMBER_TYPE),
null,
null,
true,
true,
false);
ObjectType GLOBAL_THIS = GLOBAL_THIS_CTOR.getInstanceType();
registerNativeType(JSTypeNative.GLOBAL_THIS, GLOBAL_THIS);
// greatest function type, i.e. (NoType...) -> All
FunctionType GREATEST_FUNCTION_TYPE =
createNativeFunctionTypeWithVarArgs(ALL_TYPE, NO_TYPE);
registerNativeType(JSTypeNative.GREATEST_FUNCTION_TYPE,
GREATEST_FUNCTION_TYPE);
// Register the prototype property. See the comments below in
// registerPropertyOnType about the bootstrapping process.
registerPropertyOnType("prototype", OBJECT_FUNCTION_TYPE);
}
private void initializeRegistry() {
register(getNativeType(JSTypeNative.ARRAY_TYPE));
register(getNativeType(JSTypeNative.BOOLEAN_OBJECT_TYPE));
register(getNativeType(JSTypeNative.BOOLEAN_TYPE));
register(getNativeType(JSTypeNative.ITERABLE_TYPE));
register(getNativeType(JSTypeNative.DATE_TYPE));
register(getNativeType(JSTypeNative.NULL_TYPE));
register(getNativeType(JSTypeNative.NULL_TYPE), "Null");
register(getNativeType(JSTypeNative.NUMBER_OBJECT_TYPE));
register(getNativeType(JSTypeNative.NUMBER_TYPE));
register(getNativeType(JSTypeNative.OBJECT_TYPE));
register(getNativeType(JSTypeNative.ERROR_TYPE));
register(getNativeType(JSTypeNative.URI_ERROR_TYPE));
register(getNativeType(JSTypeNative.EVAL_ERROR_TYPE));
register(getNativeType(JSTypeNative.TYPE_ERROR_TYPE));
register(getNativeType(JSTypeNative.RANGE_ERROR_TYPE));
register(getNativeType(JSTypeNative.REFERENCE_ERROR_TYPE));
register(getNativeType(JSTypeNative.SYNTAX_ERROR_TYPE));
register(getNativeType(JSTypeNative.REGEXP_TYPE));
register(getNativeType(JSTypeNative.STRING_OBJECT_TYPE));
register(getNativeType(JSTypeNative.STRING_TYPE));
register(getNativeType(JSTypeNative.SYMBOL_OBJECT_TYPE));
register(getNativeType(JSTypeNative.SYMBOL_TYPE));
register(getNativeType(JSTypeNative.VOID_TYPE));
register(getNativeType(JSTypeNative.VOID_TYPE), "Undefined");
register(getNativeType(JSTypeNative.VOID_TYPE), "void");
register(getNativeType(JSTypeNative.FUNCTION_INSTANCE_TYPE), "Function");
}
private void register(JSType type) {
register(type, type.toString());
}
private void register(JSType type, String name) {
checkArgument(!name.contains("<"), "Type names cannot contain template annotations.");
namesToTypes.put(name, type);
}
private void registerNativeType(JSTypeNative typeId, JSType type) {
nativeTypes[typeId.ordinal()] = type;
}
// When t is an object that is not the prototype of some class,
// and its nominal type is Object, and it has some properties,
// we don't need to store these properties in the propertyIndex separately.
private static boolean isObjectLiteralThatCanBeSkipped(JSType t) {
t = t.restrictByNotNullOrUndefined();
return t.isRecordType() || t.isLiteralObject();
}
void registerDroppedPropertiesInUnion(RecordType subtype, RecordType supertype) {
boolean foundDroppedProperty = false;
for (String pname : subtype.getPropertyMap().getOwnPropertyNames()) {
if (!supertype.hasProperty(pname)) {
foundDroppedProperty = true;
this.droppedPropertiesOfUnions.add(pname);
}
}
if (foundDroppedProperty) {
this.propertiesOfSupertypesInUnions.addAll(supertype.getPropertyMap().getOwnPropertyNames());
}
}
/**
* Tells the type system that {@code owner} may have a property named
* {@code propertyName}. This allows the registry to keep track of what
* types a property is defined upon.
*
* This is NOT the same as saying that {@code owner} must have a property
* named type. ObjectType#hasProperty attempts to minimize false positives
* ("if we're not sure, then don't type check this property"). The type
* registry, on the other hand, should attempt to minimize false negatives
* ("if this property is assigned anywhere in the program, it must
* show up in the type registry").
*/
public void registerPropertyOnType(String propertyName, JSType type) {
UnionTypeBuilder typeSet = typesIndexedByProperty.get(propertyName);
if (typeSet == null) {
typeSet = new UnionTypeBuilder(this, PROPERTY_CHECKING_UNION_SIZE);
typesIndexedByProperty.put(propertyName, typeSet);
}
if (isObjectLiteralThatCanBeSkipped(type)) {
type = getSentinelObjectLiteral();
}
typeSet.addAlternate(type);
addReferenceTypeIndexedByProperty(propertyName, type);
// Clear cached values that depend on typesIndexedByProperty.
greatestSubtypeByProperty.remove(propertyName);
}
private void addReferenceTypeIndexedByProperty(
String propertyName, JSType type) {
if (type instanceof ObjectType && ((ObjectType) type).hasReferenceName()) {
Map<String, ObjectType> typeSet =
eachRefTypeIndexedByProperty.get(propertyName);
if (typeSet == null) {
typeSet = new LinkedHashMap<>();
eachRefTypeIndexedByProperty.put(propertyName, typeSet);
}
ObjectType objType = (ObjectType) type;
typeSet.put(objType.getReferenceName(), objType);
} else if (type instanceof NamedType) {
addReferenceTypeIndexedByProperty(
propertyName, ((NamedType) type).getReferencedType());
} else if (type.isUnionType()) {
for (JSType alternate : type.toMaybeUnionType().getAlternates()) {
addReferenceTypeIndexedByProperty(propertyName, alternate);
}
}
}
/**
* Removes the index's reference to a property on the given type (if it is
* currently registered). If the property is not registered on the type yet,
* this method will not change internal state.
*
* @param propertyName the name of the property to unregister
* @param type the type to unregister the property on.
*/
public void unregisterPropertyOnType(String propertyName, JSType type) {
// TODO(bashir): typesIndexedByProperty should also be updated!
Map<String, ObjectType> typeSet =
eachRefTypeIndexedByProperty.get(propertyName);
if (typeSet != null) {
typeSet.remove(type.toObjectType().getReferenceName());
}
}
/**
* Gets the greatest subtype of the {@code type} that has a property
* {@code propertyName} defined on it.
*/
public JSType getGreatestSubtypeWithProperty(
JSType type, String propertyName) {
JSType withProperty = greatestSubtypeByProperty.get(propertyName);
if (withProperty != null) {
return withProperty.getGreatestSubtype(type);
}
UnionTypeBuilder typesWithProp = typesIndexedByProperty.get(propertyName);
if (typesWithProp != null) {
JSType built = typesWithProp.build();
greatestSubtypeByProperty.put(propertyName, built);
return built.getGreatestSubtype(type);
}
return getNativeType(NO_TYPE);
}
/** A tristate value returned from canPropertyBeDefined. */
public enum PropDefinitionKind {
UNKNOWN, // The property is not known to be part of this type
KNOWN, // The properties is known to be defined on a type or its super types
LOOSE, // The property is loosely associated with a type, typically one of its subtypes
LOOSE_UNION // The property is loosely associated with a union type
}
/**
* Returns whether the given property can possibly be set on the given type.
*/
public PropDefinitionKind canPropertyBeDefined(JSType type, String propertyName) {
if (type.isStruct()) {
// We are stricter about "struct" types and only allow access to
// properties that to the best of our knowledge are available at creation
// time and specifically not properties only defined on subtypes.
switch (type.getPropertyKind(propertyName)) {
case KNOWN_PRESENT:
return PropDefinitionKind.KNOWN;
case MAYBE_PRESENT:
// TODO(johnlenz): return LOOSE_UNION here.
return PropDefinitionKind.KNOWN;
case ABSENT:
return PropDefinitionKind.UNKNOWN;
}
} else {
if (!type.isEmptyType() && !type.isUnknownType()) {
switch (type.getPropertyKind(propertyName)) {
case KNOWN_PRESENT:
return PropDefinitionKind.KNOWN;
case MAYBE_PRESENT:
// TODO(johnlenz): return LOOSE_UNION here.
return PropDefinitionKind.KNOWN;
case ABSENT:
// check for loose properties below.
break;
}
}
if (typesIndexedByProperty.containsKey(propertyName)) {
for (JSType alt :
typesIndexedByProperty.get(propertyName).getAlternates()) {
JSType greatestSubtype = alt.getGreatestSubtype(type);
if (!greatestSubtype.isEmptyType()) {
// We've found a type with this property. Now we just have to make
// sure it's not a type used for internal bookkeeping.
RecordType maybeRecordType = greatestSubtype.toMaybeRecordType();
if (maybeRecordType != null && maybeRecordType.isSynthetic()) {
continue;
}
return PropDefinitionKind.LOOSE;
}
}
}
if (type.toMaybeRecordType() != null) {
RecordType rec = type.toMaybeRecordType();
boolean mayBeInUnion = false;
for (String pname : rec.getPropertyMap().getOwnPropertyNames()) {
if (this.propertiesOfSupertypesInUnions.contains(pname)) {
mayBeInUnion = true;
break;
}
}
if (mayBeInUnion && this.droppedPropertiesOfUnions.contains(propertyName)) {
return PropDefinitionKind.LOOSE;
}
}
}