-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
type_system.dart
2388 lines (2120 loc) · 83.5 KB
/
type_system.dart
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 (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library analyzer.src.generated.type_system;
import 'dart:collection';
import 'dart:math' as math;
import 'package:analyzer/dart/ast/ast.dart' show AstNode;
import 'package:analyzer/dart/ast/token.dart' show Keyword, TokenType;
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/error/listener.dart' show ErrorReporter;
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/member.dart' show TypeParameterMember;
import 'package:analyzer/src/dart/element/type.dart';
import 'package:analyzer/src/error/codes.dart' show StrongModeCode;
import 'package:analyzer/src/generated/engine.dart'
show AnalysisContext, AnalysisOptionsImpl;
import 'package:analyzer/src/generated/resolver.dart' show TypeProvider;
import 'package:analyzer/src/generated/utilities_dart.dart' show ParameterKind;
bool _isBottom(DartType t, {bool dynamicIsBottom: false}) {
return (t.isDynamic && dynamicIsBottom) ||
t.isBottom ||
t.isDartCoreNull ||
identical(t, UnknownInferredType.instance);
}
bool _isTop(DartType t, {bool dynamicIsBottom: false}) {
// TODO(leafp): Document the rules in play here
if (t.isDartAsyncFutureOr) {
return _isTop((t as InterfaceType).typeArguments[0]);
}
return (t.isDynamic && !dynamicIsBottom) ||
t.isObject ||
identical(t, UnknownInferredType.instance);
}
typedef bool _GuardedSubtypeChecker<T>(T t1, T t2, Set<TypeImpl> visitedTypes);
/**
* Implementation of [TypeSystem] using the strong mode rules.
* https://github.com/dart-lang/dev_compiler/blob/master/STRONG_MODE.md
*/
class StrongTypeSystemImpl extends TypeSystem {
static bool _comparingTypeParameterBounds = false;
/**
* True if implicit casts should be allowed, otherwise false.
*
* This affects the behavior of [isAssignableTo].
*/
final bool implicitCasts;
/**
* A list of non-nullable type names (e.g., 'int', 'bool', etc.).
*/
final List<String> nonnullableTypes;
final TypeProvider typeProvider;
StrongTypeSystemImpl(this.typeProvider,
{this.implicitCasts: true,
this.nonnullableTypes: AnalysisOptionsImpl.NONNULLABLE_TYPES});
@override
bool get isStrong => true;
bool anyParameterType(FunctionType ft, bool predicate(DartType t)) {
return ft.parameters.any((p) => predicate(p.type));
}
@override
FunctionType functionTypeToConcreteType(FunctionType t) {
// TODO(jmesserly): should we use a real "fuzzyArrow" bit on the function
// type? That would allow us to implement this in the subtype relation.
// TODO(jmesserly): we'll need to factor this differently if we want to
// move CodeChecker's functionality into existing analyzer. Likely we can
// let the Expression have a strict arrow, then in places were we do
// inference, convert back to a fuzzy arrow.
if (!t.parameters.any((p) => p.type.isDynamic)) {
return t;
}
ParameterElement shave(ParameterElement p) {
if (p.type.isDynamic) {
return new ParameterElementImpl.synthetic(
p.name, typeProvider.objectType, p.parameterKind);
}
return p;
}
List<ParameterElement> parameters = t.parameters.map(shave).toList();
FunctionElementImpl function = new FunctionElementImpl("", -1);
function.isSynthetic = true;
function.returnType = t.returnType;
function.shareTypeParameters(t.typeFormals);
function.shareParameters(parameters);
return function.type = new FunctionTypeImpl(function);
}
/**
* Given a type t, if t is an interface type with a call method
* defined, return the definite function type for the call method,
* otherwise return null.
*/
FunctionType getCallMethodDefiniteType(DartType t) {
var type = getCallMethodType(t);
if (type == null) return type;
return functionTypeToConcreteType(type);
}
/**
* Given a type t, if t is an interface type with a call method
* defined, return the function type for the call method, otherwise
* return null.
*/
FunctionType getCallMethodType(DartType t) {
if (t is InterfaceType) {
return t.lookUpInheritedMethod("call")?.type;
}
return null;
}
/// Computes the greatest lower bound of [type1] and [type2].
DartType getGreatestLowerBound(DartType type1, DartType type2,
{dynamicIsBottom: false}) {
// The greatest lower bound relation is reflexive.
if (identical(type1, type2)) {
return type1;
}
// For any type T, GLB(?, T) == T.
if (identical(type1, UnknownInferredType.instance)) {
return type2;
}
if (identical(type2, UnknownInferredType.instance)) {
return type1;
}
// The GLB of top and any type is just that type.
// Also GLB of bottom and any type is bottom.
if (_isTop(type1, dynamicIsBottom: dynamicIsBottom) ||
_isBottom(type2, dynamicIsBottom: dynamicIsBottom)) {
return type2;
}
if (_isTop(type2, dynamicIsBottom: dynamicIsBottom) ||
_isBottom(type1, dynamicIsBottom: dynamicIsBottom)) {
return type1;
}
// Treat void as top-like for GLB. This only comes into play with the
// return types of two functions whose GLB is being taken. We allow a
// non-void-returning function to subtype a void-returning one, so match
// that logic here by treating the non-void arm as the subtype for GLB.
if (type1.isVoid) {
return type2;
}
if (type2.isVoid) {
return type1;
}
// Function types have structural GLB.
if (type1 is FunctionType && type2 is FunctionType) {
return _functionGreatestLowerBound(type1, type2);
}
// Otherwise, the GLB of two types is one of them it if it is a subtype of
// the other.
if (isSubtypeOf(type1, type2)) {
return type1;
}
if (isSubtypeOf(type2, type1)) {
return type2;
}
// No subtype relation, so no known GLB.
return typeProvider.bottomType;
}
/**
* Compute the least supertype of [type], which is known to be an interface
* type.
*
* In the event that the algorithm fails (which might occur due to a bug in
* the analyzer), `null` is returned.
*/
DartType getLeastNullableSupertype(InterfaceType type) {
// compute set of supertypes
List<InterfaceType> s = InterfaceTypeImpl
.computeSuperinterfaceSet(type)
.where(isNullableType)
.toList();
return InterfaceTypeImpl.computeTypeAtMaxUniqueDepth(s);
}
/**
* Compute the least upper bound of two types.
*/
@override
DartType getLeastUpperBound(DartType type1, DartType type2,
{bool dynamicIsBottom: false}) {
if (isNullableType(type1) && isNonNullableType(type2)) {
assert(type2 is InterfaceType);
type2 = getLeastNullableSupertype(type2 as InterfaceType);
}
if (isNullableType(type2) && isNonNullableType(type1)) {
assert(type1 is InterfaceType);
type1 = getLeastNullableSupertype(type1 as InterfaceType);
}
return super
.getLeastUpperBound(type1, type2, dynamicIsBottom: dynamicIsBottom);
}
/**
* Given a generic function type `F<T0, T1, ... Tn>` and a context type C,
* infer an instantiation of F, such that `F<S0, S1, ..., Sn>` <: C.
*
* This is similar to [inferGenericFunctionOrType], but the return type is also
* considered as part of the solution.
*
* If this function is called with a [contextType] that is also
* uninstantiated, or a [fnType] that is already instantiated, it will have
* no effect and return [fnType].
*/
FunctionType inferFunctionTypeInstantiation(
FunctionType contextType, FunctionType fnType,
{ErrorReporter errorReporter, AstNode errorNode}) {
if (contextType.typeFormals.isNotEmpty || fnType.typeFormals.isEmpty) {
return fnType;
}
// Create a TypeSystem that will allow certain type parameters to be
// inferred. It will optimistically assume these type parameters can be
// subtypes (or supertypes) as necessary, and track the constraints that
// are implied by this.
var inferrer = new _GenericInferrer(typeProvider, this, fnType.typeFormals);
inferrer.constrainGenericFunctionInContext(fnType, contextType);
// Infer and instantiate the resulting type.
return inferrer.infer(fnType, fnType.typeFormals,
errorReporter: errorReporter, errorNode: errorNode);
}
/// Infers a generic type, function, method, or list/map literal
/// instantiation, using the downward context type as well as the argument
/// types if available.
///
/// For example, given a function type with generic type parameters, this
/// infers the type parameters from the actual argument types, and returns the
/// instantiated function type.
///
/// Concretely, given a function type with parameter types P0, P1, ... Pn,
/// result type R, and generic type parameters T0, T1, ... Tm, use the
/// argument types A0, A1, ... An to solve for the type parameters.
///
/// For each parameter Pi, we want to ensure that Ai <: Pi. We can do this by
/// running the subtype algorithm, and when we reach a type parameter Tj,
/// recording the lower or upper bound it must satisfy. At the end, all
/// constraints can be combined to determine the type.
///
/// All constraints on each type parameter Tj are tracked, as well as where
/// they originated, so we can issue an error message tracing back to the
/// argument values, type parameter "extends" clause, or the return type
/// context.
T inferGenericFunctionOrType<T extends ParameterizedType>(
T genericType,
List<ParameterElement> parameters,
List<DartType> argumentTypes,
DartType returnContextType,
{ErrorReporter errorReporter,
AstNode errorNode,
bool downwards: false}) {
// TODO(jmesserly): expose typeFormals on ParameterizedType.
List<TypeParameterElement> typeFormals = typeFormalsAsElements(genericType);
if (typeFormals.isEmpty) {
return genericType;
}
// Create a TypeSystem that will allow certain type parameters to be
// inferred. It will optimistically assume these type parameters can be
// subtypes (or supertypes) as necessary, and track the constraints that
// are implied by this.
var inferrer = new _GenericInferrer(typeProvider, this, typeFormals);
DartType declaredReturnType =
genericType is FunctionType ? genericType.returnType : genericType;
if (returnContextType != null) {
inferrer.constrainReturnType(declaredReturnType, returnContextType);
}
for (int i = 0; i < argumentTypes.length; i++) {
// Try to pass each argument to each parameter, recording any type
// parameter bounds that were implied by this assignment.
inferrer.constrainArgument(
argumentTypes[i], parameters[i].type, parameters[i].name,
genericType: genericType);
}
return inferrer.infer(genericType, typeFormals,
errorReporter: errorReporter,
errorNode: errorNode,
downwardsInferPhase: downwards);
}
/**
* Given a [DartType] [type], if [type] is an uninstantiated
* parameterized type then instantiate the parameters to their
* bounds. See the issue for the algorithm description.
*
* https://github.com/dart-lang/sdk/issues/27526#issuecomment-260021397
*
* TODO(scheglov) Move this method to elements for classes, typedefs,
* and generic functions; compute lazily and cache.
*/
DartType instantiateToBounds(DartType type,
{List<bool> hasError, Map<TypeParameterType, DartType> knownTypes}) {
List<TypeParameterElement> typeFormals = typeFormalsAsElements(type);
int count = typeFormals.length;
if (count == 0) {
return type;
}
Set<TypeParameterType> all = new Set<TypeParameterType>();
// all ground
Map<TypeParameterType, DartType> defaults = knownTypes ?? {};
// not ground
Map<TypeParameterType, DartType> partials = {};
for (TypeParameterElement typeParameterElement in typeFormals) {
TypeParameterType typeParameter = typeParameterElement.type;
all.add(typeParameter);
if (!defaults.containsKey(typeParameter)) {
if (typeParameter.bound == null) {
defaults[typeParameter] = DynamicTypeImpl.instance;
} else {
partials[typeParameter] = typeParameter.bound;
}
}
}
List<TypeParameterType> getFreeParameters(DartType type) {
List<TypeParameterType> parameters = null;
void appendParameters(DartType type) {
if (type is TypeParameterType && all.contains(type)) {
parameters ??= <TypeParameterType>[];
parameters.add(type);
} else if (type is ParameterizedType) {
type.typeArguments.forEach(appendParameters);
}
}
appendParameters(type);
return parameters;
}
bool hasProgress = true;
while (hasProgress) {
hasProgress = false;
for (TypeParameterType parameter in partials.keys) {
DartType value = partials[parameter];
List<TypeParameterType> freeParameters = getFreeParameters(value);
if (freeParameters == null) {
defaults[parameter] = value;
partials.remove(parameter);
hasProgress = true;
break;
} else if (freeParameters.every(defaults.containsKey)) {
defaults[parameter] = value.substitute2(
defaults.values.toList(), defaults.keys.toList());
partials.remove(parameter);
hasProgress = true;
break;
}
}
}
// If we stopped making progress, and not all types are ground,
// then the whole type is malbounded and an error should be reported
// if errors are requested, and a partially completed type should
// be returned.
if (partials.isNotEmpty) {
if (hasError != null) {
hasError[0] = true;
}
var domain = defaults.keys.toList();
var range = defaults.values.toList();
// Build a substitution Phi mapping each uncompleted type variable to
// dynamic, and each completed type variable to its default.
for (TypeParameterType parameter in partials.keys) {
domain.add(parameter);
range.add(DynamicTypeImpl.instance);
}
// Set the default for an uncompleted type variable (T extends B)
// to be Phi(B)
for (TypeParameterType parameter in partials.keys) {
defaults[parameter] = partials[parameter].substitute2(range, domain);
}
}
List<DartType> orderedArguments =
typeFormals.map((p) => defaults[p.type]).toList();
return instantiateType(type, orderedArguments);
}
@override
bool isAssignableTo(DartType fromType, DartType toType) {
// TODO(leafp): Document the rules in play here
// An actual subtype
if (isSubtypeOf(fromType, toType)) {
return true;
}
if (!implicitCasts) {
return false;
}
// Don't allow implicit downcasts between function types
// and call method objects, as these will almost always fail.
if (fromType is FunctionType && getCallMethodType(toType) != null) {
return false;
}
// Don't allow a non-generic function where a generic one is expected. The
// former wouldn't know how to handle type arguments being passed to it.
// TODO(rnystrom): This same check also exists in FunctionTypeImpl.relate()
// but we don't always reliably go through that code path. This should be
// cleaned up to avoid the redundancy.
if (fromType is FunctionType &&
toType is FunctionType &&
fromType.typeFormals.isEmpty &&
toType.typeFormals.isNotEmpty) {
return false;
}
// If the subtype relation goes the other way, allow the implicit
// downcast.
if (isSubtypeOf(toType, fromType)) {
// TODO(leafp,jmesserly): we emit warnings/hints for these in
// src/task/strong/checker.dart, which is a bit inconsistent. That
// code should be handled into places that use isAssignableTo, such as
// ErrorVerifier.
return true;
}
return false;
}
bool isGroundType(DartType t) {
// TODO(leafp): Revisit this.
if (t is TypeParameterType) {
return false;
}
if (_isTop(t)) {
return true;
}
if (t is FunctionType) {
if (!_isTop(t.returnType) ||
anyParameterType(t, (pt) => !_isBottom(pt, dynamicIsBottom: true))) {
return false;
} else {
return true;
}
}
if (t is InterfaceType) {
List<DartType> typeArguments = t.typeArguments;
for (DartType typeArgument in typeArguments) {
if (!_isTop(typeArgument)) return false;
}
return true;
}
// We should not see any other type aside from malformed code.
return false;
}
@override
bool isMoreSpecificThan(DartType t1, DartType t2) => isSubtypeOf(t1, t2);
/// Check if [type] is in a set of preselected non-nullable types.
/// [FunctionType]s are always nullable.
bool isNonNullableType(DartType type) {
return !isNullableType(type);
}
/// Opposite of [isNonNullableType].
bool isNullableType(DartType type) {
return type is FunctionType ||
!nonnullableTypes.contains(_getTypeFullyQualifiedName(type));
}
/// Check that [f1] is a subtype of [f2] for a member override.
///
/// This is different from the normal function subtyping in two ways:
/// - we know the function types are strict arrows,
/// - it allows opt-in covariant parameters.
bool isOverrideSubtypeOf(FunctionType f1, FunctionType f2) {
return FunctionTypeImpl.relate(f1, f2, isSubtypeOf, instantiateToBounds,
parameterRelation: isOverrideSubtypeOfParameter);
}
/// Check that parameter [p2] is a subtype of [p1], given that we are
/// checking `f1 <: f2` where `p1` is a parameter of `f1` and `p2` is a
/// parameter of `f2`.
///
/// Parameters are contravariant, so we must check `p2 <: p1` to
/// determine if `f1 <: f2`. This is used by [isOverrideSubtypeOf].
bool isOverrideSubtypeOfParameter(ParameterElement p1, ParameterElement p2) {
return isSubtypeOf(p2.type, p1.type) ||
p1.isCovariant && isSubtypeOf(p1.type, p2.type);
}
@override
bool isSubtypeOf(DartType leftType, DartType rightType) {
return _isSubtypeOf(leftType, rightType, null);
}
/// Given a [type] T that may have an unknown type `?`, returns a type
/// R such that R <: T for any type substituted for `?`.
///
/// In practice this will always replace `?` with either bottom or top
/// (dynamic), depending on the position of `?`.
DartType lowerBoundForType(DartType type) {
return _substituteForUnknownType(type, lowerBound: true);
}
@override
DartType refineBinaryExpressionType(DartType leftType, TokenType operator,
DartType rightType, DartType currentType) {
if (leftType is TypeParameterType &&
leftType.element.bound == typeProvider.numType) {
if (rightType == leftType || rightType == typeProvider.intType) {
if (operator == TokenType.PLUS ||
operator == TokenType.MINUS ||
operator == TokenType.STAR ||
operator == TokenType.PLUS_EQ ||
operator == TokenType.MINUS_EQ ||
operator == TokenType.STAR_EQ) {
return leftType;
}
}
if (rightType == typeProvider.doubleType) {
if (operator == TokenType.PLUS ||
operator == TokenType.MINUS ||
operator == TokenType.STAR ||
operator == TokenType.SLASH) {
return typeProvider.doubleType;
}
}
return currentType;
}
return super
.refineBinaryExpressionType(leftType, operator, rightType, currentType);
}
@override
DartType tryPromoteToType(DartType to, DartType from) {
// Allow promoting to a subtype, for example:
//
// f(Base b) {
// if (b is SubTypeOfBase) {
// // promote `b` to SubTypeOfBase for this block
// }
// }
//
// This allows the variable to be used wherever the supertype (here `Base`)
// is expected, while gaining a more precise type.
if (isSubtypeOf(to, from)) {
return to;
}
// For a type parameter `T extends U`, allow promoting the upper bound
// `U` to `S` where `S <: U`, yielding a type parameter `T extends S`.
if (from is TypeParameterType) {
if (isSubtypeOf(to, from.resolveToBound(DynamicTypeImpl.instance))) {
return new TypeParameterMember(from.element, null, to).type;
}
}
return null;
}
@override
DartType typeToConcreteType(DartType t) {
if (t is FunctionType) {
return functionTypeToConcreteType(t);
}
return t;
}
/// Given a [type] T that may have an unknown type `?`, returns a type
/// R such that T <: R for any type substituted for `?`.
///
/// In practice this will always replace `?` with either bottom or top
/// (dynamic), depending on the position of `?`.
DartType upperBoundForType(DartType type) {
return _substituteForUnknownType(type);
}
/**
* Compute the greatest lower bound of function types [f] and [g].
*
* The spec rules for GLB on function types, informally, are pretty simple:
*
* - If a parameter is required in both, it stays required.
*
* - If a positional parameter is optional or missing in one, it becomes
* optional.
*
* - Named parameters are unioned together.
*
* - For any parameter that exists in both functions, use the LUB of them as
* the resulting parameter type.
*
* - Use the GLB of their return types.
*/
DartType _functionGreatestLowerBound(FunctionType f, FunctionType g) {
// Calculate the LUB of each corresponding pair of parameters.
List<ParameterElement> parameters = [];
bool hasPositional = false;
bool hasNamed = false;
addParameter(
String name, DartType fType, DartType gType, ParameterKind kind) {
DartType paramType;
if (fType != null && gType != null) {
// If both functions have this parameter, include both of their types.
paramType = getLeastUpperBound(fType, gType, dynamicIsBottom: true);
} else {
paramType = fType ?? gType;
}
parameters.add(new ParameterElementImpl.synthetic(name, paramType, kind));
}
// TODO(rnystrom): Right now, this assumes f and g do not have any type
// parameters. Revisit that in the presence of generic methods.
List<DartType> fRequired = f.normalParameterTypes;
List<DartType> gRequired = g.normalParameterTypes;
// We need some parameter names for in the synthesized function type.
List<String> fRequiredNames = f.normalParameterNames;
List<String> gRequiredNames = g.normalParameterNames;
// Parameters that are required in both functions are required in the
// result.
int requiredCount = math.min(fRequired.length, gRequired.length);
for (int i = 0; i < requiredCount; i++) {
addParameter(fRequiredNames[i], fRequired[i], gRequired[i],
ParameterKind.REQUIRED);
}
// Parameters that are optional or missing in either end up optional.
List<DartType> fPositional = f.optionalParameterTypes;
List<DartType> gPositional = g.optionalParameterTypes;
List<String> fPositionalNames = f.optionalParameterNames;
List<String> gPositionalNames = g.optionalParameterNames;
int totalPositional = math.max(fRequired.length + fPositional.length,
gRequired.length + gPositional.length);
for (int i = requiredCount; i < totalPositional; i++) {
// Find the corresponding positional parameters (required or optional) at
// this index, if there is one.
DartType fType;
String fName;
if (i < fRequired.length) {
fType = fRequired[i];
fName = fRequiredNames[i];
} else if (i < fRequired.length + fPositional.length) {
fType = fPositional[i - fRequired.length];
fName = fPositionalNames[i - fRequired.length];
}
DartType gType;
String gName;
if (i < gRequired.length) {
gType = gRequired[i];
gName = gRequiredNames[i];
} else if (i < gRequired.length + gPositional.length) {
gType = gPositional[i - gRequired.length];
gName = gPositionalNames[i - gRequired.length];
}
// The loop should not let us go past both f and g's positional params.
assert(fType != null || gType != null);
addParameter(fName ?? gName, fType, gType, ParameterKind.POSITIONAL);
hasPositional = true;
}
// Union the named parameters together.
Map<String, DartType> fNamed = f.namedParameterTypes;
Map<String, DartType> gNamed = g.namedParameterTypes;
for (String name in fNamed.keys.toSet()..addAll(gNamed.keys)) {
addParameter(name, fNamed[name], gNamed[name], ParameterKind.NAMED);
hasNamed = true;
}
// Edge case. Dart does not support functions with both optional positional
// and named parameters. If we would synthesize that, give up.
if (hasPositional && hasNamed) return typeProvider.bottomType;
// Calculate the GLB of the return type.
DartType returnType = getGreatestLowerBound(f.returnType, g.returnType);
return new FunctionElementImpl.synthetic(parameters, returnType).type;
}
@override
DartType _functionParameterBound(DartType f, DartType g) =>
getGreatestLowerBound(f, g, dynamicIsBottom: true);
/// Given a type return its name prepended with the URI to its containing
/// library and separated by a comma.
String _getTypeFullyQualifiedName(DartType type) {
return "${type?.element?.library?.identifier},$type";
}
/**
* Guard against loops in the class hierarchy
*/
_GuardedSubtypeChecker<DartType> _guard(
_GuardedSubtypeChecker<DartType> check) {
return (DartType t1, DartType t2, Set<TypeImpl> visitedTypes) {
if (visitedTypes == null) {
visitedTypes = new HashSet<TypeImpl>();
}
if (t1 == null || !visitedTypes.add(t1)) {
return false;
}
try {
return check(t1, t2, visitedTypes);
} finally {
visitedTypes.remove(t1);
}
};
}
/**
* This currently does not implement a very complete least upper bound
* algorithm, but handles a couple of the very common cases that are
* causing pain in real code. The current algorithm is:
* 1. If either of the types is a supertype of the other, return it.
* This is in fact the best result in this case.
* 2. If the two types have the same class element, then take the
* pointwise least upper bound of the type arguments. This is again
* the best result, except that the recursive calls may not return
* the true least upper bounds. The result is guaranteed to be a
* well-formed type under the assumption that the input types were
* well-formed (and assuming that the recursive calls return
* well-formed types).
* 3. Otherwise return the spec-defined least upper bound. This will
* be an upper bound, might (or might not) be least, and might
* (or might not) be a well-formed type.
*
* TODO(leafp): Use matchTypes or something similar here to handle the
* case where one of the types is a superclass (but not supertype) of
* the other, e.g. LUB(Iterable<double>, List<int>) = Iterable<num>
* TODO(leafp): Figure out the right final algorithm and implement it.
*/
@override
DartType _interfaceLeastUpperBound(InterfaceType type1, InterfaceType type2) {
if (isSubtypeOf(type1, type2)) {
return type2;
}
if (isSubtypeOf(type2, type1)) {
return type1;
}
if (type1.element == type2.element) {
List<DartType> tArgs1 = type1.typeArguments;
List<DartType> tArgs2 = type2.typeArguments;
assert(tArgs1.length == tArgs2.length);
List<DartType> tArgs = new List(tArgs1.length);
for (int i = 0; i < tArgs1.length; i++) {
tArgs[i] = getLeastUpperBound(tArgs1[i], tArgs2[i]);
}
InterfaceTypeImpl lub = new InterfaceTypeImpl(type1.element);
lub.typeArguments = tArgs;
return lub;
}
return InterfaceTypeImpl.computeLeastUpperBound(type1, type2) ??
typeProvider.dynamicType;
}
/// Check that [f1] is a subtype of [f2].
///
/// This will always assume function types use fuzzy arrows, in other words
/// that dynamic parameters of f1 and f2 are treated as bottom.
bool _isFunctionSubtypeOf(
FunctionType f1, FunctionType f2, Set<TypeImpl> visitedTypes) {
return FunctionTypeImpl.relate(f1, f2, isSubtypeOf, instantiateToBounds,
parameterRelation: (p1, p2) => _isSubtypeOf(
p2.type, p1.type, visitedTypes,
dynamicIsBottom: true));
}
bool _isInterfaceSubtypeOf(
InterfaceType i1, InterfaceType i2, Set<TypeImpl> visitedTypes) {
if (identical(i1, i2)) {
return true;
}
// Guard recursive calls
_GuardedSubtypeChecker<InterfaceType> guardedInterfaceSubtype = _guard(
(DartType i1, DartType i2, Set<TypeImpl> visitedTypes) =>
_isInterfaceSubtypeOf(i1, i2, visitedTypes));
if (i1.element == i2.element) {
List<DartType> tArgs1 = i1.typeArguments;
List<DartType> tArgs2 = i2.typeArguments;
assert(tArgs1.length == tArgs2.length);
for (int i = 0; i < tArgs1.length; i++) {
DartType t1 = tArgs1[i];
DartType t2 = tArgs2[i];
if (!isSubtypeOf(t1, t2)) {
return false;
}
}
return true;
}
if (i2.isDartCoreFunction && i1.element.getMethod("call") != null) {
return true;
}
if (i1.isObject) {
return false;
}
if (guardedInterfaceSubtype(i1.superclass, i2, visitedTypes)) {
return true;
}
for (final parent in i1.interfaces) {
if (guardedInterfaceSubtype(parent, i2, visitedTypes)) {
return true;
}
}
for (final parent in i1.mixins) {
if (guardedInterfaceSubtype(parent, i2, visitedTypes)) {
return true;
}
}
return false;
}
bool _isSubtypeOf(DartType t1, DartType t2, Set<TypeImpl> visitedTypes,
{bool dynamicIsBottom: false}) {
if (identical(t1, t2)) {
return true;
}
// The types are void, dynamic, bottom, interface types, function types,
// FutureOr<T> and type parameters.
//
// We proceed by eliminating these different classes from consideration.
// Trivially true.
//
// Note that `?` is treated as a top and a bottom type during inference,
// so it's also covered here.
if (_isTop(t2, dynamicIsBottom: dynamicIsBottom) ||
_isBottom(t1, dynamicIsBottom: dynamicIsBottom)) {
return true;
}
// Trivially false.
if (_isTop(t1, dynamicIsBottom: dynamicIsBottom) ||
_isBottom(t2, dynamicIsBottom: dynamicIsBottom)) {
return false;
}
// Handle FutureOr<T> union type.
if (t1 is InterfaceType && t1.isDartAsyncFutureOr) {
var t1TypeArg = t1.typeArguments[0];
if (t2 is InterfaceType && t2.isDartAsyncFutureOr) {
var t2TypeArg = t2.typeArguments[0];
// FutureOr<A> <: FutureOr<B> iff A <: B
return isSubtypeOf(t1TypeArg, t2TypeArg);
}
// given t1 is Future<A> | A, then:
// (Future<A> | A) <: t2 iff Future<A> <: t2 and A <: t2.
var t1Future = typeProvider.futureType.instantiate([t1TypeArg]);
return isSubtypeOf(t1Future, t2) && isSubtypeOf(t1TypeArg, t2);
}
if (t2 is InterfaceType && t2.isDartAsyncFutureOr) {
// given t2 is Future<A> | A, then:
// t1 <: (Future<A> | A) iff t1 <: Future<A> or t1 <: A
var t2TypeArg = t2.typeArguments[0];
var t2Future = typeProvider.futureType.instantiate([t2TypeArg]);
return isSubtypeOf(t1, t2Future) || isSubtypeOf(t1, t2TypeArg);
}
// S <: T where S is a type variable
// T is not dynamic or object (handled above)
// True if T == S
// Or true if bound of S is S' and S' <: T
if (t1 is TypeParameterType) {
if (t2 is TypeParameterType &&
t1.definition == t2.definition &&
_typeParameterBoundsSubtype(t1.bound, t2.bound, true)) {
return true;
}
DartType bound = t1.element.bound;
return bound == null
? false
: _typeParameterBoundsSubtype(bound, t2, false);
}
if (t2 is TypeParameterType) {
return false;
}
// Void only appears as the return type of a function, and we handle it
// directly in the function subtype rules. We should not get to a point
// where we're doing a subtype test on a "bare" void, but just in case we
// do, handle it safely.
// TODO(rnystrom): Determine how this can ever be reached. If it can't,
// remove it.
if (t1.isVoid || t2.isVoid) {
return t1.isVoid && t2.isVoid;
}
// We've eliminated void, dynamic, bottom, type parameters, and FutureOr.
// The only cases are the combinations of interface type and function type.
// A function type can only subtype an interface type if
// the interface type is Function
if (t1 is FunctionType && t2 is InterfaceType) {
return t2.isDartCoreFunction;
}
// Guard recursive calls
_GuardedSubtypeChecker<FunctionType> guardedIsFunctionSubtype = _guard(
(DartType t1, DartType t2, Set<TypeImpl> visitedTypes) =>
_isFunctionSubtypeOf(
t1 as FunctionType, t2 as FunctionType, visitedTypes));
// An interface type can only subtype a function type if
// the interface type declares a call method with a type
// which is a super type of the function type.
if (t1 is InterfaceType && t2 is FunctionType) {
var callType = getCallMethodDefiniteType(t1);
return callType != null &&
guardedIsFunctionSubtype(callType, t2, visitedTypes);
}
// Two interface types
if (t1 is InterfaceType && t2 is InterfaceType) {
return _isInterfaceSubtypeOf(t1, t2, visitedTypes);
}
return guardedIsFunctionSubtype(t1, t2, visitedTypes);
}
DartType _substituteForUnknownType(DartType type,
{bool lowerBound: false, dynamicIsBottom: false}) {
if (identical(type, UnknownInferredType.instance)) {
if (lowerBound && !dynamicIsBottom) {
// TODO(jmesserly): this should be the bottom type, once i can be
// reified.
return typeProvider.nullType;
}
return typeProvider.dynamicType;
}
if (type is InterfaceTypeImpl) {
// Generic types are covariant, so keep the constraint direction.
var newTypeArgs = _transformList(type.typeArguments,
(t) => _substituteForUnknownType(t, lowerBound: lowerBound));
if (identical(type.typeArguments, newTypeArgs)) return type;
return new InterfaceTypeImpl(type.element, type.prunedTypedefs)
..typeArguments = newTypeArgs;
}
if (type is FunctionType) {
var parameters = type.parameters;
var returnType = type.returnType;
var newParameters = _transformList(parameters, (ParameterElement p) {
// Parameters are contravariant, so flip the constraint direction.
// Also pass dynamicIsBottom, because this is a fuzzy arrow.
var newType = _substituteForUnknownType(p.type,
lowerBound: !lowerBound, dynamicIsBottom: true);
return new ParameterElementImpl.synthetic(
p.name, newType, p.parameterKind);
});
// Return type is covariant.
var newReturnType =
_substituteForUnknownType(returnType, lowerBound: lowerBound);
if (identical(parameters, newParameters) &&