-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
FunctionType.java
1513 lines (1419 loc) · 55.8 KB
/
FunctionType.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2013 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp.newtypes;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import com.google.javascript.rhino.TypeI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Additional type information for methods and stand-alone functions.
* Stored as a field in appropriate {@link ObjectType} instances.
*
* @author blickly@google.com (Ben Lickly)
* @author dimvar@google.com (Dimitris Vardoulakis)
*/
public final class FunctionType {
private final JSTypes commonTypes;
private final ImmutableList<JSType> requiredFormals;
private final ImmutableList<JSType> optionalFormals;
private final JSType restFormals;
private final JSType returnType;
private final boolean isLoose;
private final boolean isAbstract;
private final ImmutableMap<String, JSType> outerVarPreconditions;
// If this FunctionType is a constructor/interface, this field stores the
// type of the instance.
private final JSType nominalType;
// If this FunctionType is a prototype method, this field stores the
// type of the instance.
private final JSType receiverType;
// Non-empty iff this function has an @template annotation. Note that a function type can have
// type variables as formal parameters and still have empty typeParameters, eg, a method without
// @template defined on a generic class.
private final ImmutableList<String> typeParameters;
private static final boolean DEBUGGING = false;
private FunctionType(
JSTypes commonTypes,
ImmutableList<JSType> requiredFormals,
ImmutableList<JSType> optionalFormals,
JSType restFormals,
JSType retType,
JSType nominalType,
JSType receiverType,
ImmutableMap<String, JSType> outerVars,
ImmutableList<String> typeParameters,
boolean isLoose,
boolean isAbstract) {
Preconditions.checkNotNull(commonTypes);
this.commonTypes = commonTypes;
this.requiredFormals = requiredFormals;
this.optionalFormals = optionalFormals;
this.restFormals = restFormals;
this.returnType = retType;
this.nominalType = nominalType;
this.receiverType = receiverType;
this.outerVarPreconditions = outerVars;
this.typeParameters = typeParameters;
this.isLoose = isLoose;
this.isAbstract = isAbstract;
checkValid();
}
// This constructor is only used to create TOP_FUNCTION and LOOSE_TOP_FUNCTION.
// We create only one TOP_FUNCTION and one LOOSE_TOP_FUNCTION, and check
// for "topness" using reference equality. Most fields of these two types are set to null,
// and are not allowed to be null for other function types. This is on purpose;
// we do not want to accidentally make a top function be equals() to some other
// function type. The return type is unknown for convenience.
private FunctionType(JSTypes commonTypes, boolean isLoose) {
Preconditions.checkNotNull(commonTypes);
this.commonTypes = commonTypes;
this.requiredFormals = null;
this.optionalFormals = null;
this.restFormals = null;
this.returnType = Preconditions.checkNotNull(this.commonTypes.UNKNOWN);
this.nominalType = null;
this.receiverType = null;
this.outerVarPreconditions = null;
this.typeParameters = ImmutableList.of();
this.isLoose = isLoose;
this.isAbstract = false;
}
/**
* Checks a number of preconditions on the function, ensuring that it has
* been properly initialized. This is called automatically by all public
* factory methods. Only TOP_FUNCTION and LOOSE_TOP_FUNCTION are not
* validated.
*/
@SuppressWarnings("ReferenceEquality")
private void checkValid() {
if (isTopFunction() || isQmarkFunction()) {
return;
}
Preconditions.checkNotNull(requiredFormals,
"null required formals for function: %s", this);
for (JSType formal : requiredFormals) {
Preconditions.checkNotNull(formal);
// A loose function has bottom formals in the bwd direction of NTI.
// See NTI#analyzeLooseCallNodeBwd.
Preconditions.checkState(isLoose || !formal.isBottom());
}
Preconditions.checkNotNull(optionalFormals,
"null optional formals for function: %s", this);
for (JSType formal : optionalFormals) {
Preconditions.checkNotNull(formal);
Preconditions.checkState(!formal.isBottom());
}
Preconditions.checkState(restFormals == null || !restFormals.isBottom());
Preconditions.checkNotNull(returnType);
}
/** Returns the JSTypes instance stored by this object. */
JSTypes getCommonTypes() {
return this.commonTypes;
}
/**
* Returns true if this function type is "loose". When an unannotated formal parameter of
* some function is itself used as a function, we infer a loose function type for it.
* For example: {@code function f(g) { return g(5) - 2; }}. Here, g is a loose number→number
* function. A loose function type may have required formal parameters that are bottom.
*/
public boolean isLoose() {
return isLoose;
}
/**
* Returns a loose version of this function type, for example, as the result of
* specializing or joining this function with a "loose top" or "question mark"
* function (in both of these cases, no formal parameters need to be combined).
*/
FunctionType withLoose() {
if (isLoose()) {
return this;
}
if (isTopFunction()) {
return this.commonTypes.LOOSE_TOP_FUNCTION;
}
return new FunctionType(
this.commonTypes,
requiredFormals, optionalFormals, restFormals, returnType, nominalType,
receiverType, outerVarPreconditions, typeParameters, true, isAbstract);
}
public boolean isAbstract() {
return isAbstract;
}
public boolean isConstructorOfAbstractClass() {
return isUniqueConstructor()
&& this.nominalType.getNominalTypeIfSingletonObj().isAbstractClass();
}
/**
* Builds a function type, adjusting its inputs to a "canonical" form if necessary, e.g.,
* replacing null arguments with empty collections. Optional parameters whose types are equal to
* the rest type are also removed.
*/
static FunctionType normalized(
JSTypes commonTypes,
List<JSType> requiredFormals,
List<JSType> optionalFormals,
JSType restFormals,
JSType retType,
JSType nominalType,
JSType receiverType,
Map<String, JSType> outerVars,
ImmutableList<String> typeParameters,
boolean isLoose,
boolean isAbstract) {
if (requiredFormals == null) {
requiredFormals = ImmutableList.of();
}
if (optionalFormals == null) {
optionalFormals = ImmutableList.of();
}
if (outerVars == null) {
outerVars = ImmutableMap.of();
}
if (typeParameters == null) {
typeParameters = ImmutableList.of();
}
if (restFormals != null) {
// Remove trailing optional params w/ type equal to restFormals
for (int i = optionalFormals.size() - 1; i >= 0; i--) {
if (restFormals.equals(optionalFormals.get(i))) {
optionalFormals.remove(i);
} else {
break;
}
}
}
return new FunctionType(
commonTypes,
ImmutableList.copyOf(requiredFormals),
ImmutableList.copyOf(optionalFormals),
restFormals, retType, nominalType, receiverType,
ImmutableMap.copyOf(outerVars),
typeParameters,
isLoose,
isAbstract);
}
/**
* Called in the beginning of type checking, when the JSTypes object is being initialized.
* Creates a few basic function types:
* TOP_FUNCTION, a supertype of all functions;
* LOOSE_TOP_FUNCTION, same as top but loose;
* QMARK_FUNCTION, the "any" function; a subtype and supertype of all function types; and
* BOTTOM_FUNCTION, a subtype of all functions.
*/
static Map<String, FunctionType> createInitialFunctionTypes(JSTypes commonTypes) {
LinkedHashMap<String, FunctionType> functions = new LinkedHashMap<>();
functions.put(
"QMARK_FUNCTION",
FunctionType.normalized(
commonTypes, null, null, commonTypes.UNKNOWN, commonTypes.UNKNOWN,
null, null, null, null, true, false));
functions.put(
"BOTTOM_FUNCTION",
FunctionType.normalized(
commonTypes, null, null, null, commonTypes.BOTTOM, null, null, null, null, false,
false));
functions.put("TOP_FUNCTION", new FunctionType(commonTypes, false));
functions.put("LOOSE_TOP_FUNCTION", new FunctionType(commonTypes, true));
return functions;
}
/**
* Returns true if this function is either version (loose or not) of the
* top function (which takes all bottoms and returns top).
*/
@SuppressWarnings("ReferenceEquality")
public boolean isTopFunction() {
return this == this.commonTypes.TOP_FUNCTION || this == this.commonTypes.LOOSE_TOP_FUNCTION;
}
/** Null-safe version of {@link JSType#getNominalTypeIfSingletonObj}. */
private static NominalType getNominalTypeIfSingletonObj(JSType t) {
return t == null ? null : t.getNominalTypeIfSingletonObj();
}
/**
* Returns true if this type is some sort of constructor, i.e. function(new: T)
* for any value of T (whether it be a class, interface, type variable, or union
* thereof). This is a looser version of {@link #isUniqueConstructor} and
* {@link #isInterfaceDefinition}.
*/
public boolean isSomeConstructorOrInterface() {
return this.nominalType != null;
}
/**
* Returns true if this is a constructor for a single class, i.e.
* function(new: Foo} where Foo is a concrete class.
*/
public boolean isUniqueConstructor() {
NominalType nt = getNominalTypeIfSingletonObj(this.nominalType);
return nt != null && nt.isClass();
}
/**
* Returns true if this is a constructor for a single interface, i.e.
* function(new: Foo} where Foo is an interface definition.
*/
public boolean isInterfaceDefinition() {
NominalType nt = getNominalTypeIfSingletonObj(this.nominalType);
return nt != null && nt.isInterface();
}
/**
* Returns the prototype object of the superclass, or null if there is
* no superclass.
*
* @throws IllegalStateException if this is not a unique constructor.
*/
public JSType getSuperPrototype() {
Preconditions.checkState(isUniqueConstructor());
NominalType nt = getNominalTypeIfSingletonObj(this.nominalType);
NominalType superClass = nt.getInstantiatedSuperclass();
return superClass == null ? null : superClass.getPrototypePropertyOfCtor();
}
/**
* Returns true if this function is the common QMARK_FUNCTION type
* (function(...?): ?), determined by reference equality.
*/
@SuppressWarnings("ReferenceEquality")
public boolean isQmarkFunction() {
return this == this.commonTypes.QMARK_FUNCTION;
}
/**
* Returns true if there exist any function values that can inhabit the given function type.
* (In our type system, this is true for all non-bottom function types.)
*/
@SuppressWarnings("ReferenceEquality")
static boolean isInhabitable(FunctionType f) {
return f == null || f != f.commonTypes.BOTTOM_FUNCTION;
}
public boolean hasRestFormals() {
return restFormals != null;
}
/**
* Returns the type of this function's rest parameter.
*
* @throws IllegalStateException if there is no rest parameter.
*/
public JSType getRestFormalsType() {
Preconditions.checkNotNull(restFormals);
return restFormals;
}
/**
* Returns the formal parameter in the given (0-indexed) position,
* or null if the position is past the end of the parameter list.
*
* @throws IllegalStateException if this is the top function (rather than returning bottom).
*/
public JSType getFormalType(int argpos) {
Preconditions.checkState(!isTopFunction());
int numReqFormals = requiredFormals.size();
if (argpos < numReqFormals) {
return requiredFormals.get(argpos);
} else if (argpos < numReqFormals + optionalFormals.size()) {
return optionalFormals.get(argpos - numReqFormals);
} else {
// Note: as requiredFormals and optionalFormals are both ImmutableLists,
// they can never return null. This is the only codepath that can return
// null, and only if there is no rest parameter.
return restFormals;
}
}
public JSType getReturnType() {
return returnType;
}
/**
* Returns the type of the closed-over variable of the given name,
* or null if the named variable is not in the closure.
*
* @throws IllegalStateException if this is the top function.
*/
public JSType getOuterVarPrecondition(String name) {
Preconditions.checkState(!isTopFunction());
return outerVarPreconditions.get(name);
}
/**
* Returns the minimum number of parameters accepted by this function.
*
* @throws IllegalStateException if this is the top function, which has
* effectively-infinite minimum arity.
*/
public int getMinArity() {
Preconditions.checkState(!isTopFunction());
return requiredFormals.size();
}
/**
* Returns the maximum number of parameters accepted by this function,
* or Integer.MAX_VALUE for a function with rest parameters (effectively
* infinite).
*
* @throws IllegalStateException if this is the top function.
*/
public int getMaxArity() {
Preconditions.checkArgument(!isTopFunction());
if (restFormals != null) {
return Integer.MAX_VALUE; // "Infinite" arity
} else {
return requiredFormals.size() + optionalFormals.size();
}
}
/**
* Returns the maximum number of parameters accepted by this function,
* not counting rest parameters.
*
* @throws IllegalStateException if this is the top function.
*/
public int getMaxArityWithoutRestFormals() {
return requiredFormals.size() + optionalFormals.size();
}
/** Returns true if the {@code i}th parameter is required. */
public boolean isRequiredArg(int i) {
return i < requiredFormals.size();
}
/** Returns true if the {@code i}th parameter is an optional parameter. */
public boolean isOptionalArg(int i) {
return i >= requiredFormals.size()
&& i < requiredFormals.size() + optionalFormals.size();
}
/**
* If this type is a constructor (e.g. function(new: Foo)), returns the
* type Foo. If the nominal type is generic, then type parameters are
* set to unknown. Returns null for non-constructors.
*/
public JSType getInstanceTypeOfCtor() {
if (!isGeneric()) {
return this.nominalType;
}
NominalType nominal = getNominalTypeIfSingletonObj(this.nominalType);
return nominal == null
? null
: nominal.instantiateGenerics(this.commonTypes.MAP_TO_UNKNOWN).getInstanceAsJSType();
}
/**
* Returns the 'this' type of the function, or the 'new' type for a
* constructor.
*/
public JSType getThisType() {
return this.receiverType != null ? this.receiverType : this.nominalType;
}
/**
* Say a method f is defined on a generic type {@code Foo<T>}.
* When doing Foo.prototype.f.call (or also .apply), we transform the method type to a
* function F, which includes the type variables of Foo, in this case T.
*/
private FunctionTypeBuilder transformCallApplyHelper() {
FunctionTypeBuilder builder = new FunctionTypeBuilder(this.commonTypes);
if (this.receiverType == null) {
builder.addReqFormal(this.commonTypes.UNKNOWN);
return builder;
}
NominalType nt = this.receiverType.getNominalTypeIfSingletonObj();
if (nt != null && nt.isUninstantiatedGenericType()) {
builder.addTypeParameters(nt.getTypeParameters());
NominalType ntWithIdentity = nt.instantiateGenericsWithIdentity();
builder.addReqFormal(JSType.fromObjectType(ObjectType.fromNominalType(ntWithIdentity)));
} else {
builder.addReqFormal(this.receiverType);
}
return builder;
}
/**
* Returns a FunctionType representing the 'call' property of this
* function (i.e. the receiver type is prepended to the parameter list).
*/
public FunctionType transformByCallProperty() {
if (isTopFunction() || isQmarkFunction() || isLoose) {
return this.commonTypes.QMARK_FUNCTION;
}
FunctionTypeBuilder builder = transformCallApplyHelper();
for (JSType type : this.requiredFormals) {
builder.addReqFormal(type);
}
for (JSType type : this.optionalFormals) {
builder.addOptFormal(type);
}
builder.addRestFormals(this.restFormals);
builder.addRetType(this.returnType);
builder.appendTypeParameters(this.typeParameters);
builder.addAbstract(this.isAbstract);
return builder.buildFunction();
}
/**
* Returns a FunctionType representing the 'apply' property of this
* function. In most cases, only the receiver type is checked, since
* heterogeneous parameter types are not representable without tuples
* in the type system (or other special handling). If the only
* parameter is a rest parameter, then the array argument is typed
* correctly.
*/
public FunctionType transformByApplyProperty() {
if (isTopFunction() || isQmarkFunction() || isLoose) {
return this.commonTypes.QMARK_FUNCTION;
}
if (isGeneric()) {
return instantiateGenericsWithUnknown().transformByApplyProperty();
}
FunctionTypeBuilder builder = transformCallApplyHelper();
JSType arrayContents;
if (getMaxArityWithoutRestFormals() == 0 && hasRestFormals()) {
arrayContents = getRestFormalsType();
} else {
arrayContents = this.commonTypes.UNKNOWN;
}
JSType varargsArray = this.commonTypes.getIArrayLikeInstance(arrayContents);
builder.addOptFormal(JSType.join(this.commonTypes.NULL, varargsArray));
builder.addRetType(this.returnType);
builder.addAbstract(this.isAbstract);
return builder.buildFunction();
}
/**
* Returns this function type as a {@link DeclaredFunctionType}. While
* DeclaredFunctionType allows incomplete types (i.e. null formals or
* returns), this function always returns a complete type. This should
* only be called from GlobalTypeInfo.
*
* @throws IllegalStateException if this function is loose.
*/
public DeclaredFunctionType toDeclaredFunctionType() {
if (isQmarkFunction()) {
return DeclaredFunctionType.qmarkFunctionDeclaration(this.commonTypes);
}
Preconditions.checkState(!isLoose(), "Loose function: %s", this);
FunctionTypeBuilder builder = new FunctionTypeBuilder(this.commonTypes);
if (isGeneric()) {
builder.addTypeParameters(this.typeParameters);
}
for (JSType type : this.requiredFormals) {
builder.addReqFormal(type);
}
for (JSType type : this.optionalFormals) {
builder.addOptFormal(type);
}
builder.addRestFormals(this.restFormals);
builder.addRetType(this.returnType);
builder.addNominalType(this.nominalType);
builder.addReceiverType(this.receiverType);
builder.addAbstract(this.isAbstract);
return builder.buildDeclaration();
}
/**
* Null-safe version of {@link JSType#meet}, treating nulls as top.
* Returns null if both inputs are null, or if the result would be
* bottom.
*/
private static JSType nullAcceptingMeet(JSType t1, JSType t2) {
if (t1 == null) {
return t2;
}
if (t2 == null) {
return t1;
}
JSType tmp = JSType.meet(t1, t2);
return tmp.isBottom() ? null : tmp;
}
/**
* Merges a loose function type with another function. This is strictly
* neither a join nor a meet, but instead joins both the formals and
* the return. This behavior is appropriate since loose functions are
* the result of inferring facts about an unannotated function type,
* so seeing it accept or return a particular type only allows adding
* types to the union of types alread seen in that position.
*/
// TODO(dimvar): we need to clean up the combination of loose functions with
// new: and/or this: types. Eg, this.nominalType doesn't appear at all.
private static FunctionType looseMerge(FunctionType f1, FunctionType f2) {
Preconditions.checkArgument(f1.isLoose() || f2.isLoose());
FunctionTypeBuilder builder = new FunctionTypeBuilder(f1.commonTypes);
int minRequiredArity = Math.min(f1.getMinArity(), f2.getMinArity());
for (int i = 0; i < minRequiredArity; i++) {
builder.addReqFormal(JSType.nullAcceptingJoin(
f1.getFormalType(i), f2.getFormalType(i)));
}
int maxTotalArity = Math.max(
f1.requiredFormals.size() + f1.optionalFormals.size(),
f2.requiredFormals.size() + f2.optionalFormals.size());
for (int i = minRequiredArity; i < maxTotalArity; i++) {
JSType t = JSType.nullAcceptingJoin(f1.getFormalType(i), f2.getFormalType(i));
if (t != null && t.isBottom()) {
// We will add the optional formal of the loose function in the fwd
// direction, when we have better type information.
break;
}
builder.addOptFormal(t);
}
// Loose types never have varargs, because there is no way for that
// information to make it to a function summary
return builder.addRetType(
JSType.nullAcceptingJoin(f1.returnType, f2.returnType))
.addLoose().buildFunction();
}
/**
* Returns true if this function is a valid override of other.
* Specifically, this requires that this function be a subtype of other.
*/
public boolean isValidOverride(FunctionType other) {
// Note: SubtypeCache.create() is cheap, since the data structure is persistent.
// The cache is used to handle cycles in types' dependencies.
return isSubtypeOfHelper(other, false, SubtypeCache.create(), null);
}
// We want to warn about argument mismatch, so we don't consider a function
// with N required arguments to have restFormals of type TOP.
// But we allow joins (eg after an IF) to change arity, eg,
// number->number ∨ number,number->number = number,number->number
/** Returns true if this function is a subtype of {@code other}. */
boolean isSubtypeOf(FunctionType other, SubtypeCache subSuperMap) {
return isSubtypeOfHelper(other, true, subSuperMap, null);
}
/**
* Fills boxedInfo with the reason why f1 is not a subtype of f2,
* for the purpose of building informative error messages.
*/
static void whyNotSubtypeOf(FunctionType f1, FunctionType f2,
SubtypeCache subSuperMap, MismatchInfo[] boxedInfo) {
Preconditions.checkArgument(boxedInfo.length == 1);
f1.isSubtypeOfHelper(f2, true, subSuperMap, boxedInfo);
}
/**
* Returns true if this function's formal parameter list is exactly
* {@code ...?}. This notation has a special meaning: it is NOT a
* variable-arity function with arguments of ? type; it means that
* we should skip type-checking the arguments. We can therefore use
* it to represent, for example, a constructor of Foos with whatever
* arguments.
*/
private boolean acceptsAnyArguments() {
return this.requiredFormals.isEmpty() && this.optionalFormals.isEmpty()
&& this.restFormals != null && this.restFormals.isUnknown();
}
/**
* Recursively checks that this is a subtype of other: this's parameter
* types are supertypes of other's corresponding parameters (contravariant),
* and this's return type is a subtype of other's return type (covariant).
* Additionally, any 'this' type must be contravariant and any 'new' type
* must be covariant. A cache is used to resolve cycles, and details
* about some mismatched types are written to boxedInfo[0].
*/
private boolean isSubtypeOfHelper(FunctionType other, boolean checkThisType,
SubtypeCache subSuperMap, MismatchInfo[] boxedInfo) {
if (other.isTopFunction() ||
other.isQmarkFunction() || this.isQmarkFunction()) {
return true;
}
if (isTopFunction()) {
return false;
}
// NOTE(dimvar): We never happen to call isSubtypeOf for loose functions.
// If some analyzed program changes this, the preconditions check will tell
// us so we can handle looseness correctly.
Preconditions.checkState(!isLoose() && !other.isLoose());
if (this.isGeneric()) {
if (this.equals(other)) {
return true;
}
// NOTE(dimvar): This is a bug. The code that triggers this should be rare
// and the fix is not trivial, so for now we decided to not fix.
// See unit tests in NewTypeInferenceTest#testGenericsSubtyping
return instantiateGenericsWithUnknown()
.isSubtypeOfHelper(other, checkThisType, subSuperMap, boxedInfo);
}
if (!other.acceptsAnyArguments()) {
// The subtype must have an equal or smaller number of required formals
if (requiredFormals.size() > other.requiredFormals.size()) {
return false;
}
int otherMaxTotalArity =
other.requiredFormals.size() + other.optionalFormals.size();
for (int i = 0; i < otherMaxTotalArity; i++) {
// contravariance in the arguments
JSType thisFormal = getFormalType(i);
JSType otherFormal = other.getFormalType(i);
if (thisFormal != null
&& !thisFormal.isUnknown() && !otherFormal.isUnknown()
&& !otherFormal.isSubtypeOf(thisFormal, subSuperMap)) {
if (boxedInfo != null) {
boxedInfo[0] =
MismatchInfo.makeArgTypeMismatch(i, otherFormal, thisFormal);
}
return false;
}
}
if (other.restFormals != null) {
int thisMaxTotalArity =
this.requiredFormals.size() + this.optionalFormals.size();
if (this.restFormals != null) {
thisMaxTotalArity++;
}
for (int i = otherMaxTotalArity; i < thisMaxTotalArity; i++) {
JSType thisFormal = getFormalType(i);
JSType otherFormal = other.getFormalType(i);
if (thisFormal != null
&& !thisFormal.isUnknown() && !otherFormal.isUnknown()
&& !otherFormal.isSubtypeOf(thisFormal, subSuperMap)) {
return false;
}
}
}
}
// covariance for the new: type
if ((this.nominalType == null && other.nominalType != null)
|| (this.nominalType != null && other.nominalType != null
&& !this.nominalType.isSubtypeOf(other.nominalType, subSuperMap))) {
return false;
}
if (checkThisType) {
// A function without @this can be a subtype of a function with @this.
if (!this.commonTypes.allowMethodsAsFunctions
&& this.receiverType != null && other.receiverType == null) {
return false;
}
if (this.receiverType != null && other.receiverType != null
// Contravariance for the receiver type
&& !other.receiverType.isSubtypeOf(this.receiverType, subSuperMap)) {
return false;
}
}
// covariance in the return type
boolean areRetTypesSubtypes = this.returnType.isUnknown()
|| other.returnType.isUnknown()
|| this.returnType.isSubtypeOf(other.returnType, subSuperMap);
if (boxedInfo != null) {
boxedInfo[0] =
MismatchInfo.makeRetTypeMismatch(other.returnType, this.returnType);
}
return areRetTypesSubtypes;
}
/**
* Returns the join of two nominal types. Optimized to avoid using
* {@link JSType#join} if possible to prevent creating new types.
* Null arguments (and returns) are treated as top. This is called
* by {@link #join} and {@link #meet}.
*/
private static JSType joinNominalTypes(JSType nt1, JSType nt2) {
if (nt1 == null || nt2 == null) {
return null;
}
NominalType n1 = getNominalTypeIfSingletonObj(nt1);
NominalType n2 = getNominalTypeIfSingletonObj(nt2);
if (n1 != null && n2 != null) {
NominalType tmp = NominalType.join(n1, n2);
if (tmp != null) {
return tmp.getInstanceAsJSType();
}
}
// One of the nominal types is non-standard; can't avoid the join
return JSType.join(nt1, nt2);
}
/**
* Returns the meet of two nominal types. Optimized to avoid using
* {@link JSType#meet} if possible to prevent creating new types.
* Null arguments (and returns) are treated as top. This is called
* by {@link #join} and {@link #meet}.
*/
private static JSType meetNominalTypes(JSType nt1, JSType nt2) {
if (nt1 == null) {
return nt2;
}
if (nt2 == null) {
return nt1;
}
NominalType n1 = getNominalTypeIfSingletonObj(nt1);
NominalType n2 = getNominalTypeIfSingletonObj(nt2);
if (n1 != null && n2 != null) {
NominalType tmp = NominalType.pickSubclass(n1, n2);
return tmp == null ? null : tmp.getInstanceAsJSType();
}
// One of the nominal types is non-standard; can't avoid the meet
return JSType.meet(nt1, nt2);
}
/**
* Returns the join (union) of two function types. The return type is
* the join of the input return types. The formal parameters are the
* meets of the input functions' parameters (where required ∧ optional
* is required). Generic functions will lose precision if they are
* not in a direct subclass relationship. If any parameter meets to
* bottom, then BOTTOM_FUNCTION will be returned. Nominal ("new")
* types are joined (they are in "output" position), while receiver
* ("this") types are intersected (they are in "input" position).
*/
static FunctionType join(FunctionType f1, FunctionType f2) {
if (f1 == null) {
return f2;
} else if (f2 == null || f1.equals(f2)) {
return f1;
} else if (f1.isQmarkFunction() || f2.isQmarkFunction()) {
return f1.commonTypes.QMARK_FUNCTION;
} else if (f1.isTopFunction() || f2.isTopFunction()) {
return f1.commonTypes.TOP_FUNCTION;
}
if (f1.isLoose() || f2.isLoose()) {
return looseMerge(f1, f2);
}
if (f1.isGeneric() && f2.isSubtypeOf(f1, SubtypeCache.create())) {
return f1;
} else if (f2.isGeneric() && f1.isSubtypeOf(f2, SubtypeCache.create())) {
return f2;
}
// We lose precision for generic funs that are not in a subtype relation.
if (f1.isGeneric()) {
f1 = f1.instantiateGenericsWithUnknown();
}
if (f2.isGeneric()) {
f2 = f2.instantiateGenericsWithUnknown();
}
JSTypes commonTypes = f1.commonTypes;
FunctionTypeBuilder builder = new FunctionTypeBuilder(commonTypes);
int maxRequiredArity = Math.max(
f1.requiredFormals.size(), f2.requiredFormals.size());
for (int i = 0; i < maxRequiredArity; i++) {
JSType reqFormal = nullAcceptingMeet(f1.getFormalType(i), f2.getFormalType(i));
if (reqFormal == null) {
return commonTypes.BOTTOM_FUNCTION;
}
builder.addReqFormal(reqFormal);
}
int maxTotalArity = Math.max(
f1.requiredFormals.size() + f1.optionalFormals.size(),
f2.requiredFormals.size() + f2.optionalFormals.size());
for (int i = maxRequiredArity; i < maxTotalArity; i++) {
JSType optFormal = nullAcceptingMeet(f1.getFormalType(i), f2.getFormalType(i));
if (optFormal == null) {
return commonTypes.BOTTOM_FUNCTION;
}
builder.addOptFormal(optFormal);
}
if (f1.restFormals != null && f2.restFormals != null) {
JSType newRestFormals = nullAcceptingMeet(f1.restFormals, f2.restFormals);
if (newRestFormals == null) {
return commonTypes.BOTTOM_FUNCTION;
}
builder.addRestFormals(newRestFormals);
}
builder.addRetType(JSType.join(f1.returnType, f2.returnType));
builder.addNominalType(joinNominalTypes(f1.nominalType, f2.nominalType));
builder.addReceiverType(meetNominalTypes(f1.receiverType, f2.receiverType));
return builder.buildFunction();
}
/**
* Specializes this function with the {@code other} function type. It's often
* a no-op, because when this type is not loose, no specialization is required.
*/
FunctionType specialize(FunctionType other) {
if (other == null
|| other.isQmarkFunction() || other.isTopFunction() || equals(other)
|| !isLoose()) {
return this;
}
return isTopFunction() || isQmarkFunction()
? other.withLoose() : looseMerge(this, other);
}
/**
* Returns the meet (intersect) of two function types. The return
* type is the meet of the input returns. The formal parameters
* are the joins of the input functions' parameters (where required
* ∨ optional is optional). Generic functions will lose precision
* if they are not in a direct subclass relationship. If any
* parameter or return results in bottom, then BOTTOM_FUNCTION will
* be returned. Nominal ("new") types are intersected, while
* receiver ("this") types are joined.
*/
static FunctionType meet(FunctionType f1, FunctionType f2) {
if (f1 == null || f2 == null) {
return null;
} else if (f2.isTopFunction() || f1.equals(f2)) {
return f1;
} else if (f1.isTopFunction()) {
return f2;
}
if (f1.isLoose() || f2.isLoose()) {
return looseMerge(f1, f2);
}
if (f1.isGeneric() && f1.isSubtypeOf(f2, SubtypeCache.create())) {
return f1;
} else if (f2.isGeneric() && f2.isSubtypeOf(f1, SubtypeCache.create())) {
return f2;
}
// We lose precision for generic funs that are not in a subtype relation.
if (f1.isGeneric()) {
f1 = f1.instantiateGenericsWithUnknown();
}
if (f2.isGeneric()) {
f2 = f2.instantiateGenericsWithUnknown();
}
JSTypes commonTypes = f1.commonTypes;
FunctionTypeBuilder builder = new FunctionTypeBuilder(commonTypes);
int minRequiredArity = Math.min(
f1.requiredFormals.size(), f2.requiredFormals.size());
for (int i = 0; i < minRequiredArity; i++) {
builder.addReqFormal(
JSType.nullAcceptingJoin(f1.getFormalType(i), f2.getFormalType(i)));
}
int maxTotalArity = Math.max(
f1.requiredFormals.size() + f1.optionalFormals.size(),
f2.requiredFormals.size() + f2.optionalFormals.size());
for (int i = minRequiredArity; i < maxTotalArity; i++) {
JSType optFormalType =
JSType.nullAcceptingJoin(f1.getFormalType(i), f2.getFormalType(i));
if (optFormalType.isBottom()) {
return commonTypes.BOTTOM_FUNCTION;
}
builder.addOptFormal(optFormalType);
}
if (f1.restFormals != null || f2.restFormals != null) {
JSType restFormalsType =
JSType.nullAcceptingJoin(f1.restFormals, f2.restFormals);
if (restFormalsType.isBottom()) {
return commonTypes.BOTTOM_FUNCTION;
}
builder.addRestFormals(restFormalsType);
}
JSType retType = JSType.meet(f1.returnType, f2.returnType);
if (retType.isBottom()) {
return commonTypes.BOTTOM_FUNCTION;
}
builder.addRetType(retType);
// NOTE(dimvar): these two are not correct. We should be picking the
// greatest lower bound of the types if they are incomparable.
// Eg, this case arises when an interface extends multiple interfaces.
// OTOH, it may be enough to detect that during GTI, and not implement the
// more expensive methods (in NominalType or ObjectType).
builder.addNominalType(meetNominalTypes(f1.nominalType, f2.nominalType));
builder.addReceiverType(joinNominalTypes(f1.receiverType, f2.receiverType));
return builder.buildFunction();
}
/**
* Returns true if this function or {@code f2} is a possibly subtype of the
* other. This requires that all required parameters and the return type
* share a common subtype.
*
* <p>We may consider true subtyping for deferred checks when the formal
* parameter has a loose function type.
*
* @throws IllegalStateException if neither function is loose.
*/
// TODO(sdh): make this method static to emphasize parameter symmetry.
boolean isLooseSubtypeOf(FunctionType f2) {
Preconditions.checkState(this.isLoose() || f2.isLoose());
if (this.isTopFunction() || f2.isTopFunction()) {
return true;
}
int minRequiredArity =
Math.min(this.requiredFormals.size(), f2.requiredFormals.size());
for (int i = 0; i < minRequiredArity; i++) {
if (!JSType.haveCommonSubtype(this.getFormalType(i), f2.getFormalType(i))) {
return false;
}
}
return JSType.haveCommonSubtype(this.getReturnType(), f2.getReturnType());
}
/**
* Returns true if this function has any non-instantiated type parameters.
* (Note: if this type is the result of a generic function type that has been
* instantiated, the type parameters have already been substituted away.)
*/
public boolean isGeneric() {
return !this.typeParameters.isEmpty();
}