-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathsource_class_builder.dart
2302 lines (2147 loc) · 88 KB
/
source_class_builder.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) 2016, 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.
import 'package:kernel/ast.dart';
import 'package:kernel/class_hierarchy.dart'
show ClassHierarchy, ClassHierarchyBase, ClassHierarchyMembers;
import 'package:kernel/core_types.dart';
import 'package:kernel/names.dart' show equalsName;
import 'package:kernel/reference_from_index.dart'
show IndexedClass, IndexedLibrary;
import 'package:kernel/src/bounds_checks.dart';
import 'package:kernel/src/types.dart' show Types;
import 'package:kernel/type_algebra.dart'
show
FreshTypeParameters,
Substitution,
getFreshTypeParameters,
substitute,
updateBoundNullabilities;
import 'package:kernel/type_environment.dart';
import '../base/messages.dart';
import '../base/modifiers.dart';
import '../base/name_space.dart';
import '../base/problems.dart' show unexpected, unhandled, unimplemented;
import '../base/scope.dart';
import '../builder/augmentation_iterator.dart';
import '../builder/builder.dart';
import '../builder/declaration_builders.dart';
import '../builder/formal_parameter_builder.dart';
import '../builder/library_builder.dart';
import '../builder/member_builder.dart';
import '../builder/name_iterator.dart';
import '../builder/named_type_builder.dart';
import '../builder/never_type_declaration_builder.dart';
import '../builder/nullability_builder.dart';
import '../builder/synthesized_type_builder.dart';
import '../builder/type_builder.dart';
import '../fragment/fragment.dart';
import '../kernel/body_builder_context.dart';
import '../kernel/hierarchy/hierarchy_builder.dart';
import '../kernel/hierarchy/hierarchy_node.dart';
import '../kernel/kernel_helper.dart';
import '../kernel/type_algorithms.dart';
import '../kernel/utils.dart' show compareProcedures;
import 'builder_factory.dart';
import 'class_declaration.dart';
import 'name_scheme.dart';
import 'source_builder_mixins.dart';
import 'source_constructor_builder.dart';
import 'source_factory_builder.dart';
import 'source_library_builder.dart';
import 'source_loader.dart';
import 'source_member_builder.dart';
import 'source_type_parameter_builder.dart';
import 'type_parameter_scope_builder.dart';
Class initializeClass(
List<SourceNominalParameterBuilder>? typeParameters,
String name,
Uri fileUri,
int startOffset,
int nameOffset,
int endOffset,
IndexedClass? indexedClass,
{required bool isAugmentation}) {
Class cls = new Class(
name: name,
typeParameters: SourceNominalParameterBuilder.typeParametersFromBuilders(
typeParameters),
// If the class is an augmentation class it shouldn't use the reference
// from index even when available.
// TODO(johnniwinther): Avoid creating [Class] so early in the builder
// that we end up creating unneeded nodes.
reference: isAugmentation ? null : indexedClass?.reference,
fileUri: fileUri);
if (cls.startFileOffset == TreeNode.noOffset) {
cls.startFileOffset = startOffset;
}
if (cls.fileOffset == TreeNode.noOffset) {
cls.fileOffset = nameOffset;
}
if (cls.fileEndOffset == TreeNode.noOffset) {
cls.fileEndOffset = endOffset;
}
return cls;
}
class SourceClassBuilder extends ClassBuilderImpl
implements
Comparable<SourceClassBuilder>,
ClassDeclarationBuilder,
SourceDeclarationBuilder {
@override
final SourceLibraryBuilder libraryBuilder;
final int nameOffset;
@override
final String name;
@override
final Uri fileUri;
final Modifiers _modifiers;
@override
final Class cls;
final DeclarationNameSpaceBuilder nameSpaceBuilder;
late final DeclarationNameSpace _nameSpace;
@override
List<SourceNominalParameterBuilder>? typeParameters;
/// The scope in which the [typeParameters] are declared.
final LookupScope typeParameterScope;
TypeBuilder? _supertypeBuilder;
List<TypeBuilder>? _interfaceBuilders;
TypeBuilder? _mixedInTypeBuilder;
final IndexedClass? indexedClass;
bool? _isConflictingAugmentationMember;
/// Returns `true` if this class is a class declared in an augmentation
/// library that conflicts with a declaration in the origin library.
bool get isConflictingAugmentationMember {
return _isConflictingAugmentationMember ??= false;
}
// Coverage-ignore(suite): Not run.
void set isConflictingAugmentationMember(bool value) {
assert(_isConflictingAugmentationMember == null,
'$this.isConflictingAugmentationMember has already been fixed.');
_isConflictingAugmentationMember = value;
}
final ClassDeclaration _introductory;
List<ClassDeclaration> _augmentations;
SourceClassBuilder(
{required Modifiers modifiers,
required this.name,
required this.typeParameters,
required this.typeParameterScope,
required this.nameSpaceBuilder,
required this.libraryBuilder,
required this.fileUri,
required this.nameOffset,
this.indexedClass,
TypeBuilder? mixedInTypeBuilder,
required ClassDeclaration introductory,
List<ClassDeclaration> augmentations = const []})
: _modifiers = modifiers,
_introductory = introductory,
_augmentations = augmentations,
_mixedInTypeBuilder = mixedInTypeBuilder,
cls = initializeClass(
typeParameters,
name,
fileUri,
introductory.startOffset,
introductory.nameOffset,
introductory.endOffset,
indexedClass,
isAugmentation: modifiers.isAugment) {
cls.hasConstConstructor = declaresConstConstructor;
}
@override
int resolveConstructors(SourceLibraryBuilder libraryBuilder) {
int count = _introductory.resolveConstructorReferences(libraryBuilder);
for (ClassDeclaration augmentation in _augmentations) {
count += augmentation.resolveConstructorReferences(libraryBuilder);
}
if (count > 0) {
Iterator<MemberBuilder> iterator =
nameSpace.filteredConstructorIterator(includeDuplicates: true);
while (iterator.moveNext()) {
MemberBuilder declaration = iterator.current;
if (declaration.declarationBuilder != this) {
unexpected("$fileUri", "${declaration.declarationBuilder!.fileUri}",
fileOffset, fileUri);
}
if (declaration is SourceFactoryBuilder) {
declaration.resolveRedirectingFactory();
}
}
}
return count;
}
@override
int get fileOffset => nameOffset;
@override
bool get isAbstract => _modifiers.isAbstract;
@override
bool get isNamedMixinApplication {
return isMixinApplication && _modifiers.isNamedMixinApplication;
}
@override
bool get declaresConstConstructor => _modifiers.declaresConstConstructor;
@override
bool get isSealed => _modifiers.isSealed;
@override
bool get isBase => _modifiers.isBase;
@override
bool get isInterface => _modifiers.isInterface;
@override
bool get isFinal => _modifiers.isFinal;
/// Set to `true` if this class is declared using the `augment` modifier.
bool get isAugmentation => _modifiers.isAugment;
@override
bool get isMixinClass => _modifiers.isMixin;
@override
// Coverage-ignore(suite): Not run.
bool get isConst => _modifiers.isConst;
@override
// Coverage-ignore(suite): Not run.
bool get isStatic => _modifiers.isStatic;
@override
bool get isAugment => _modifiers.isAugment;
@override
bool get isMixinDeclaration => _introductory.isMixinDeclaration;
@override
DeclarationNameSpace get nameSpace => _nameSpace;
@override
void buildScopes(LibraryBuilder coreLibrary) {
_nameSpace = nameSpaceBuilder.buildNameSpace(
loader: libraryBuilder.loader,
problemReporting: libraryBuilder,
enclosingLibraryBuilder: libraryBuilder,
declarationBuilder: this,
indexedLibrary: libraryBuilder.indexedLibrary,
indexedContainer: indexedClass,
containerType: ContainerType.Class,
containerName: new ClassName(name));
}
bool _hasComputedSupertypes = false;
void computeSupertypeBuilder({
required SourceLoader loader,
required ProblemReporting problemReporting,
required List<NominalParameterBuilder> unboundNominalParameters,
required IndexedLibrary? indexedLibrary,
required Map<SourceClassBuilder, TypeBuilder> mixinApplications,
required void Function(SourceClassBuilder) addAnonymousMixinClassBuilder,
}) {
assert(!_hasComputedSupertypes, "Supertypes have already been computed.");
_hasComputedSupertypes = true;
_supertypeBuilder = _applyMixins(
unboundNominalParameters: unboundNominalParameters,
compilationUnitScope: _introductory.compilationUnitScope,
problemReporting: problemReporting,
objectTypeBuilder: loader.target.objectType,
enclosingLibraryBuilder: libraryBuilder,
fileUri: _introductory.fileUri,
indexedLibrary: indexedLibrary,
supertype: _introductory.supertype,
mixins: _introductory.mixedInTypes,
mixinApplications: mixinApplications,
startOffset: _introductory.startOffset,
nameOffset: _introductory.nameOffset,
endOffset: _introductory.endOffset,
subclassName: _introductory.name,
isMixinDeclaration: _introductory.isMixinDeclaration,
typeParameters: typeParameters,
modifiers: Modifiers.empty,
onAnonymousMixin: (SourceClassBuilder anonymousMixinBuilder) {
Reference? reference = anonymousMixinBuilder.indexedClass?.reference;
if (reference != null) {
loader.buildersCreatedWithReferences[reference] =
anonymousMixinBuilder;
}
addAnonymousMixinClassBuilder(anonymousMixinBuilder);
anonymousMixinBuilder.buildScopes(loader.coreLibrary);
});
_interfaceBuilders = _introductory.interfaces;
}
void markAsCyclic(ClassBuilder objectClass) {
assert(_hasComputedSupertypes,
"Supertype of $this has not been computed yet.");
// Ensure that the cycle is broken by removing superclass and
// implemented interfaces.
cls.implementedTypes.clear();
cls.supertype = null;
cls.mixedInType = null;
_supertypeBuilder = new NamedTypeBuilderImpl.fromTypeDeclarationBuilder(
objectClass, const NullabilityBuilder.omitted(),
instanceTypeParameterAccess:
InstanceTypeParameterAccessState.Unexpected);
_interfaceBuilders = null;
_mixedInTypeBuilder = null;
// TODO(johnniwinther): Update the message for when a class depends on
// a cycle but does not depend on itself.
addProblem(templateCyclicClassHierarchy.withArguments(fullNameForErrors),
fileOffset, noLength);
}
// Coverage-ignore(suite): Not run.
/// Check that this class, which is the `Object` class, has no supertypes.
/// Recover by removing any found.
void checkObjectSupertypes() {
if (_supertypeBuilder != null) {
_supertypeBuilder = null;
addProblem(messageObjectExtends, fileOffset, noLength);
}
if (_interfaceBuilders != null) {
addProblem(messageObjectImplements, fileOffset, noLength);
_interfaceBuilders = null;
}
if (_mixedInTypeBuilder != null) {
addProblem(messageObjectMixesIn, fileOffset, noLength);
_mixedInTypeBuilder = null;
}
}
void installDefaultSupertypes(
ClassBuilder objectClassBuilder, Class objectClass) {
if (objectClass != cls) {
cls.supertype ??= objectClass.asRawSupertype;
_supertypeBuilder ??= new NamedTypeBuilderImpl.fromTypeDeclarationBuilder(
objectClassBuilder, const NullabilityBuilder.omitted(),
instanceTypeParameterAccess:
InstanceTypeParameterAccessState.Unexpected);
}
if (isMixinApplication) {
cls.mixedInType = mixedInTypeBuilder!.buildMixedInType(libraryBuilder);
}
}
@override
TypeBuilder? get supertypeBuilder {
assert(_hasComputedSupertypes,
"Supertype of $this has not been computed yet.");
return _supertypeBuilder;
}
@override
SourceLibraryBuilder get parent => libraryBuilder;
Class build(LibraryBuilder coreLibrary) {
void buildBuilders(Builder declaration) {
if (declaration.parent != this) {
// Coverage-ignore-block(suite): Not run.
if (declaration.parent != this) {
if (fileUri != declaration.parent?.fileUri) {
unexpected("$fileUri", "${declaration.parent?.fileUri}", fileOffset,
fileUri);
} else {
unexpected(
fullNameForErrors,
declaration.parent?.fullNameForErrors ?? '',
fileOffset,
fileUri);
}
}
} else if (declaration is SourceMemberBuilder) {
SourceMemberBuilder memberBuilder = declaration;
memberBuilder.buildOutlineNodes((
{required Member member,
Member? tearOff,
required BuiltMemberKind kind}) {
_addMemberToClass(declaration, member);
if (tearOff != null) {
_addMemberToClass(declaration, tearOff);
}
});
} else {
unhandled("${declaration.runtimeType}", "buildBuilders",
declaration.fileOffset, declaration.fileUri);
}
}
nameSpace.unfilteredIterator.forEach(buildBuilders);
nameSpace.unfilteredConstructorIterator.forEach(buildBuilders);
if (_supertypeBuilder != null) {
_supertypeBuilder = _checkSupertype(_supertypeBuilder!);
}
TypeDeclarationBuilder? supertypeDeclaration =
supertypeBuilder?.computeUnaliasedDeclaration(isUsedAsClass: false);
if (LibraryBuilder.isFunction(supertypeDeclaration, coreLibrary)) {
_supertypeBuilder = null;
}
Supertype? supertype = supertypeBuilder?.buildSupertype(libraryBuilder,
isMixinDeclaration ? TypeUse.mixinOnType : TypeUse.classExtendsType);
if (!isMixinDeclaration &&
cls.supertype != null &&
// Coverage-ignore(suite): Not run.
cls.superclass!.isMixinDeclaration) {
// Coverage-ignore-block(suite): Not run.
// Declared mixins have interfaces that can be implemented, but they
// cannot be extended. However, a mixin declaration with a single
// superclass constraint is encoded with the constraint as the supertype,
// and that is allowed to be a mixin's interface.
libraryBuilder.addProblem(
templateSupertypeIsIllegal.withArguments(cls.superclass!.name),
fileOffset,
noLength,
fileUri);
supertype = null;
}
if (supertype == null && _supertypeBuilder is! NamedTypeBuilder) {
_supertypeBuilder = null;
}
cls.supertype = supertype;
if (_mixedInTypeBuilder != null) {
_mixedInTypeBuilder = _checkSupertype(_mixedInTypeBuilder!);
}
TypeDeclarationBuilder? mixedInDeclaration =
_mixedInTypeBuilder?.computeUnaliasedDeclaration(isUsedAsClass: false);
if (LibraryBuilder.isFunction(mixedInDeclaration, coreLibrary)) {
_mixedInTypeBuilder = null;
cls.isAnonymousMixin = false;
}
Supertype? mixedInType =
_mixedInTypeBuilder?.buildMixedInType(libraryBuilder);
cls.isMixinDeclaration = isMixinDeclaration;
cls.mixedInType = mixedInType;
// TODO(ahe): If `cls.supertype` is null, and this isn't Object, report a
// compile-time error.
cls.isAbstract = isAbstract;
cls.isMixinClass = isMixinClass;
cls.isSealed = isSealed;
cls.isBase = isBase;
cls.isInterface = isInterface;
cls.isFinal = isFinal;
List<TypeBuilder>? interfaceBuilders = this.interfaceBuilders;
if (interfaceBuilders != null) {
for (int i = 0; i < interfaceBuilders.length; ++i) {
interfaceBuilders[i] = _checkSupertype(interfaceBuilders[i]);
TypeDeclarationBuilder? implementedDeclaration = interfaceBuilders[i]
.computeUnaliasedDeclaration(isUsedAsClass: false);
if (LibraryBuilder.isFunction(implementedDeclaration, coreLibrary) &&
// Allow wasm to implement `Function`.
!libraryBuilder.mayImplementRestrictedTypes) {
continue;
}
Supertype? supertype = interfaceBuilders[i]
.buildSupertype(libraryBuilder, TypeUse.classImplementsType);
if (supertype != null) {
// TODO(ahe): Report an error if supertype is null.
cls.implementedTypes.add(supertype);
}
}
}
cls.procedures.sort(compareProcedures);
return cls;
}
@override
List<TypeBuilder>? get interfaceBuilders {
assert(_hasComputedSupertypes, "Interfaces have not been computed yet.");
return _interfaceBuilders;
}
@override
TypeBuilder? get mixedInTypeBuilder => _mixedInTypeBuilder;
void setInferredMixedInTypeArguments(List<TypeBuilder> typeArguments) {
InterfaceType mixedInType = cls.mixedInType!.asInterfaceType;
TypeBuilder mixedInTypeBuilder = _mixedInTypeBuilder!;
_mixedInTypeBuilder = new NamedTypeBuilderImpl.forDartType(
mixedInType,
mixedInTypeBuilder.declaration!,
new NullabilityBuilder.fromNullability(Nullability.nonNullable),
arguments: typeArguments,
fileUri: mixedInTypeBuilder.fileUri,
charOffset: mixedInTypeBuilder.charOffset);
libraryBuilder.registerBoundsCheck(mixedInType, mixedInTypeBuilder.fileUri!,
mixedInTypeBuilder.charOffset!, TypeUse.classWithType,
inferred: true);
}
BodyBuilderContext createBodyBuilderContext() {
return new ClassBodyBuilderContext(this);
}
void buildOutlineExpressions(ClassHierarchy classHierarchy,
List<DelayedDefaultValueCloner> delayedDefaultValueCloners) {
void build(Builder declaration) {
SourceMemberBuilder member = declaration as SourceMemberBuilder;
member.buildOutlineExpressions(
classHierarchy, delayedDefaultValueCloners);
}
BodyBuilderContext bodyBuilderContext = createBodyBuilderContext();
_introductory.buildOutlineExpressions(
annotatable: cls,
bodyBuilderContext: bodyBuilderContext,
libraryBuilder: libraryBuilder,
classHierarchy: classHierarchy,
createFileUriExpression: false);
for (ClassDeclaration augmentation in _augmentations) {
augmentation.buildOutlineExpressions(
annotatable: cls,
bodyBuilderContext: bodyBuilderContext,
classHierarchy: classHierarchy,
libraryBuilder: libraryBuilder,
createFileUriExpression: true);
}
if (typeParameters != null) {
for (int i = 0; i < typeParameters!.length; i++) {
typeParameters![i].buildOutlineExpressions(
libraryBuilder, bodyBuilderContext, classHierarchy);
}
}
nameSpace
.filteredConstructorIterator(includeDuplicates: false)
.forEach(build);
nameSpace.filteredIterator(includeDuplicates: false).forEach(build);
}
@override
Iterator<T> fullMemberIterator<T extends Builder>() =>
nameSpace.filteredIterator<T>(includeDuplicates: false);
@override
// Coverage-ignore(suite): Not run.
NameIterator<T> fullMemberNameIterator<T extends Builder>() =>
nameSpace.filteredNameIterator<T>(includeDuplicates: false);
@override
Iterator<T> fullConstructorIterator<T extends MemberBuilder>() =>
nameSpace.filteredConstructorIterator<T>(includeDuplicates: false);
@override
NameIterator<T> fullConstructorNameIterator<T extends MemberBuilder>() =>
nameSpace.filteredConstructorNameIterator<T>(includeDuplicates: false);
/// Looks up the constructor by [name] on the class built by this class
/// builder.
SourceConstructorBuilder? lookupConstructor(Name name) {
if (name.text == "new") {
name = new Name("", name.library);
}
Builder? builder = nameSpace.lookupConstructor(name.text);
if (builder is SourceConstructorBuilder) {
return builder;
}
return null;
}
/// Looks up the super constructor by [name] on the superclass of the class
/// built by this class builder.
Constructor? lookupSuperConstructor(Name name) {
if (name.text == "new") {
name = new Name("", name.library);
}
Class? superclass = cls.superclass;
if (superclass != null) {
for (Constructor constructor in superclass.constructors) {
if (constructor.name == name) {
return constructor;
}
}
}
return null;
}
@override
int get typeParametersCount => typeParameters?.length ?? 0;
@override
List<DartType> buildAliasedTypeArguments(LibraryBuilder library,
List<TypeBuilder>? arguments, ClassHierarchyBase? hierarchy) {
if (arguments == null && typeParameters == null) {
return <DartType>[];
}
if (arguments == null && typeParameters != null) {
// TODO(johnniwinther): Use i2b here when needed.
List<DartType> result = new List<DartType>.generate(
typeParameters!.length,
(int i) => typeParameters![i]
.defaultType!
// TODO(johnniwinther): Using [libraryBuilder] here instead of
// [library] preserves the nullability of the original
// declaration. Should we legacy erase this?
.buildAliased(
libraryBuilder, TypeUse.defaultTypeAsTypeArgument, hierarchy),
growable: true);
return result;
}
if (arguments != null && arguments.length != typeParametersCount) {
// Coverage-ignore-block(suite): Not run.
assert(libraryBuilder.loader.assertProblemReportedElsewhere(
"SourceClassBuilder.buildAliasedTypeArguments: "
"the numbers of type parameters and type arguments don't match.",
expectedPhase: CompilationPhaseForProblemReporting.outline));
return unhandled(
templateTypeArgumentMismatch
.withArguments(typeParametersCount)
.problemMessage,
"buildTypeArguments",
-1,
null);
}
assert(arguments!.length == typeParametersCount);
List<DartType> result = new List<DartType>.generate(
arguments!.length,
(int i) =>
arguments[i].buildAliased(library, TypeUse.typeArgument, hierarchy),
growable: true);
return result;
}
/// Returns a map which maps the type parameters of [superclass] to their
/// respective values as defined by the superclass clause of this class (and
/// its superclasses).
///
/// It's assumed that [superclass] is a superclass of this class.
///
/// For example, given:
///
/// class Box<T> {}
/// class BeatBox extends Box<Beat> {}
/// class Beat {}
///
/// We have:
///
/// [[BeatBox]].getSubstitutionMap([[Box]]) -> {[[Box::T]]: Beat]]}.
///
/// It's an error if [superclass] isn't a superclass.
Map<TypeParameter, DartType> getSubstitutionMap(Class superclass) {
Supertype? supertype = cls.supertype;
Map<TypeParameter, DartType> substitutionMap = <TypeParameter, DartType>{};
List<DartType> arguments;
List<TypeParameter> variables;
Class? classNode;
while (classNode != superclass) {
classNode = supertype!.classNode;
arguments = supertype.typeArguments;
variables = classNode.typeParameters;
supertype = classNode.supertype;
if (variables.isNotEmpty) {
Map<TypeParameter, DartType> directSubstitutionMap =
<TypeParameter, DartType>{};
for (int i = 0; i < variables.length; i++) {
DartType argument =
i < arguments.length ? arguments[i] : const DynamicType();
// TODO(ahe): Investigate if requiring the caller to use
// `substituteDeep` from `package:kernel/type_algebra.dart` instead
// of `substitute` is faster. If so, we can simply this code.
argument = substitute(argument, substitutionMap);
directSubstitutionMap[variables[i]] = argument;
}
substitutionMap = directSubstitutionMap;
}
}
return substitutionMap;
}
void checkSupertypes(
CoreTypes coreTypes,
ClassHierarchyBuilder hierarchyBuilder,
Class objectClass,
Class enumClass,
Class underscoreEnumClass) {
// This method determines whether the class (that's being built) its super
// class appears both in 'extends' and 'implements' clauses and whether any
// interface appears multiple times in the 'implements' clause.
// Moreover, it checks that `FutureOr` and `void` are not among the
// supertypes and that `Enum` is not implemented by non-abstract classes.
// Anonymous mixins have to propagate certain class modifiers.
if (cls.isAnonymousMixin) {
Class? superclass = cls.superclass;
Class? mixedInClass = cls.mixedInClass;
// If either [superclass] or [mixedInClass] is sealed, the current
// anonymous mixin is sealed.
if (superclass != null && superclass.isSealed ||
mixedInClass != null && mixedInClass.isSealed) {
cls.isSealed = true;
} else {
// Otherwise, if either [superclass] or [mixedInClass] is base or final,
// then the current anonymous mixin is final.
bool superclassIsBaseOrFinal =
superclass != null && (superclass.isBase || superclass.isFinal);
bool mixedInClassIsBaseOrFinal = mixedInClass != null &&
(mixedInClass.isBase || mixedInClass.isFinal);
if (superclassIsBaseOrFinal || mixedInClassIsBaseOrFinal) {
cls.isFinal = true;
}
}
}
ClassHierarchyNode classHierarchyNode =
hierarchyBuilder.getNodeFromClass(cls);
if (libraryBuilder.libraryFeatures.enhancedEnums.isEnabled && !isEnum) {
bool hasEnumSuperinterface = false;
const List<String> restrictedNames = ["index", "hashCode", "=="];
Map<String, ClassBuilder> restrictedMembersInSuperclasses = {};
ClassBuilder? superclassDeclaringConcreteValues;
List<Supertype> interfaces = classHierarchyNode.superclasses;
for (int i = 0; !hasEnumSuperinterface && i < interfaces.length; i++) {
Class interfaceClass = interfaces[i].classNode;
if (interfaceClass == enumClass) {
hasEnumSuperinterface = true;
}
if (!interfaceClass.isEnum &&
interfaceClass != objectClass &&
interfaceClass != underscoreEnumClass) {
ClassHierarchyNode superclassHierarchyNode =
hierarchyBuilder.getNodeFromClass(interfaceClass);
for (String restrictedMemberName in restrictedNames) {
// TODO(johnniwinther): Handle injected members.
Builder? member = superclassHierarchyNode.classBuilder.nameSpace
.lookupLocalMember(restrictedMemberName, setter: false);
if (member is MemberBuilder && !member.isAbstract) {
restrictedMembersInSuperclasses[restrictedMemberName] ??=
superclassHierarchyNode.classBuilder;
}
}
Builder? member = superclassHierarchyNode.classBuilder.nameSpace
.lookupLocalMember("values", setter: false);
if (member is MemberBuilder && !member.isAbstract) {
superclassDeclaringConcreteValues ??= member.classBuilder;
}
}
}
interfaces = classHierarchyNode.interfaces;
for (int i = 0; !hasEnumSuperinterface && i < interfaces.length; i++) {
if (interfaces[i].classNode == enumClass) {
hasEnumSuperinterface = true;
}
}
if (!cls.isAbstract && !cls.isEnum && hasEnumSuperinterface) {
addProblem(templateEnumSupertypeOfNonAbstractClass.withArguments(name),
fileOffset, noLength);
}
if (hasEnumSuperinterface && cls != underscoreEnumClass) {
// Instance members named `values` are restricted.
Builder? customValuesDeclaration =
nameSpace.lookupLocalMember("values", setter: false);
if (customValuesDeclaration != null &&
!customValuesDeclaration.isStatic) {
// Retrieve the earliest declaration for error reporting.
while (customValuesDeclaration?.next != null) {
// Coverage-ignore-block(suite): Not run.
customValuesDeclaration = customValuesDeclaration?.next;
}
libraryBuilder.addProblem(
templateEnumImplementerContainsValuesDeclaration
.withArguments(this.name),
customValuesDeclaration!.fileOffset,
customValuesDeclaration.fullNameForErrors.length,
fileUri);
}
customValuesDeclaration =
nameSpace.lookupLocalMember("values", setter: true);
if (customValuesDeclaration != null &&
!customValuesDeclaration.isStatic) {
// Retrieve the earliest declaration for error reporting.
while (customValuesDeclaration?.next != null) {
// Coverage-ignore-block(suite): Not run.
customValuesDeclaration = customValuesDeclaration?.next;
}
libraryBuilder.addProblem(
templateEnumImplementerContainsValuesDeclaration
.withArguments(this.name),
customValuesDeclaration!.fileOffset,
customValuesDeclaration.fullNameForErrors.length,
fileUri);
}
if (superclassDeclaringConcreteValues != null) {
libraryBuilder.addProblem(
templateInheritedRestrictedMemberOfEnumImplementer.withArguments(
"values", superclassDeclaringConcreteValues.name),
fileOffset,
noLength,
fileUri);
}
// Non-setter concrete instance members named `index` and hashCode and
// operator == are restricted.
for (String restrictedMemberName in restrictedNames) {
Builder? member =
nameSpace.lookupLocalMember(restrictedMemberName, setter: false);
if (member is MemberBuilder && !member.isAbstract) {
libraryBuilder.addProblem(
templateEnumImplementerContainsRestrictedInstanceDeclaration
.withArguments(this.name, restrictedMemberName),
member.fileOffset,
member.fullNameForErrors.length,
fileUri);
}
if (restrictedMembersInSuperclasses
.containsKey(restrictedMemberName)) {
ClassBuilder restrictedNameMemberProvider =
restrictedMembersInSuperclasses[restrictedMemberName]!;
libraryBuilder.addProblem(
templateInheritedRestrictedMemberOfEnumImplementer
.withArguments(restrictedMemberName,
restrictedNameMemberProvider.name),
fileOffset,
noLength,
fileUri);
}
}
}
}
void fail(TypeBuilder target, Message message,
TypeDeclarationBuilder? aliasBuilder) {
int nameOffset = target.typeName!.nameOffset;
int nameLength = target.typeName!.nameLength;
if (aliasBuilder is TypeAliasBuilder) {
// Coverage-ignore-block(suite): Not run.
addProblem(message, nameOffset, nameLength, context: [
messageTypedefCause.withLocation(
aliasBuilder.fileUri, aliasBuilder.fileOffset, noLength),
]);
} else {
addProblem(message, nameOffset, nameLength);
}
}
// Extract and check superclass (if it exists).
ClassBuilder? superClass;
TypeBuilder? superClassType = supertypeBuilder;
if (superClassType != null) {
TypeDeclarationBuilder? superDeclaration = superClassType.declaration;
TypeDeclarationBuilder? unaliasedSuperDeclaration =
superClassType.computeUnaliasedDeclaration(isUsedAsClass: true);
// TODO(eernst): Should gather 'restricted supertype' checks in one place,
// e.g., dynamic/int/String/Null and more are checked elsewhere.
if (unaliasedSuperDeclaration is NeverTypeDeclarationBuilder) {
fail(superClassType, messageExtendsNever, superDeclaration);
} else if (unaliasedSuperDeclaration is ClassBuilder) {
superClass = unaliasedSuperDeclaration;
}
}
if (cls.isMixinClass) {
// Check that the class does not have a constructor.
Iterator<SourceMemberBuilder> constructorIterator =
fullConstructorIterator<SourceMemberBuilder>();
while (constructorIterator.moveNext()) {
SourceMemberBuilder constructor = constructorIterator.current;
// Assumes the constructor isn't synthetic since
// [installSyntheticConstructors] hasn't been called yet.
if (constructor is SourceConstructorBuilderImpl) {
// Report an error if a mixin class has a constructor with parameters,
// is external, or is a redirecting constructor.
if (constructor.isRedirecting ||
constructor.hasParameters ||
constructor.isExternal) {
addProblem(
templateIllegalMixinDueToConstructors
.withArguments(fullNameForErrors),
constructor.fileOffset,
noLength);
}
}
}
// Check that the class has 'Object' as their superclass.
if (superClass != null &&
superClassType != null &&
superClass.cls != objectClass) {
addProblem(templateMixinInheritsFromNotObject.withArguments(name),
superClassType.charOffset ?? TreeNode.noOffset, noLength);
}
}
if (classHierarchyNode.isMixinApplication) {
assert(_mixedInTypeBuilder != null,
"No mixed in type builder for mixin application $this.");
ClassHierarchyNode mixedInNode = classHierarchyNode.mixedInNode!;
ClassHierarchyNode? mixinSuperClassNode =
mixedInNode.directSuperClassNode;
if (mixinSuperClassNode != null &&
mixinSuperClassNode.classBuilder.cls != objectClass &&
!mixedInNode.classBuilder.cls.isMixinDeclaration) {
addProblem(
templateMixinInheritsFromNotObject
.withArguments(mixedInNode.classBuilder.name),
_mixedInTypeBuilder!.charOffset ?? TreeNode.noOffset,
noLength);
}
}
if (interfaceBuilders == null) return;
// Validate interfaces.
Map<ClassBuilder, int>? problems;
Map<ClassBuilder, int>? problemsOffsets;
Set<ClassBuilder> implemented = new Set<ClassBuilder>();
for (TypeBuilder type in interfaceBuilders!) {
TypeDeclarationBuilder? typeDeclaration = type.declaration;
TypeDeclarationBuilder? unaliasedDeclaration =
type.computeUnaliasedDeclaration(isUsedAsClass: true);
if (unaliasedDeclaration is ClassBuilder) {
ClassBuilder interface = unaliasedDeclaration;
if (superClass == interface) {
addProblem(templateImplementsSuperClass.withArguments(interface.name),
this.fileOffset, noLength);
} else if (interface.cls.name == "FutureOr" &&
// Coverage-ignore(suite): Not run.
interface.cls.enclosingLibrary.importUri.isScheme("dart") &&
// Coverage-ignore(suite): Not run.
interface.cls.enclosingLibrary.importUri.path == "async") {
// Coverage-ignore-block(suite): Not run.
addProblem(messageImplementsFutureOr, this.fileOffset, noLength);
} else if (implemented.contains(interface)) {
// Aggregate repetitions.
problems ??= <ClassBuilder, int>{};
problems[interface] ??= 0;
problems[interface] = problems[interface]! + 1;
problemsOffsets ??= <ClassBuilder, int>{};
problemsOffsets[interface] ??= type.charOffset ?? TreeNode.noOffset;
} else {
implemented.add(interface);
}
}
if (unaliasedDeclaration != superClass) {
// TODO(eernst): Have all 'restricted supertype' checks in one place.
if (unaliasedDeclaration is NeverTypeDeclarationBuilder) {
fail(type, messageImplementsNever, typeDeclaration);
}
}
}
if (problems != null) {
problems.forEach((ClassBuilder interface, int repetitions) {
addProblem(
templateImplementsRepeated.withArguments(
interface.name, repetitions),
problemsOffsets![interface]!,
noLength);
});
}
}
void checkMixinApplication(ClassHierarchy hierarchy, CoreTypes coreTypes) {
TypeEnvironment typeEnvironment = new TypeEnvironment(coreTypes, hierarchy);
// A mixin declaration can only be applied to a class that implements all
// the declaration's superclass constraints.
InterfaceType supertype = cls.supertype!.asInterfaceType;
Substitution substitution = Substitution.fromSupertype(cls.mixedInType!);
for (Supertype constraint in cls.mixedInClass!.onClause) {
InterfaceType requiredInterface =
substitution.substituteSupertype(constraint).asInterfaceType;
InterfaceType? implementedInterface =
hierarchy.getInterfaceTypeAsInstanceOfClass(
supertype, requiredInterface.classNode);
if (implementedInterface == null ||
!typeEnvironment.areMutualSubtypes(implementedInterface,
requiredInterface, SubtypeCheckMode.withNullabilities)) {
libraryBuilder.addProblem(
templateMixinApplicationIncompatibleSupertype.withArguments(
supertype, requiredInterface, cls.mixedInType!.asInterfaceType),
cls.fileOffset,
noLength,
cls.fileUri);
}
}
}
void checkRedirectingFactories(TypeEnvironment typeEnvironment) {
Iterator<SourceFactoryBuilder> iterator =
nameSpace.filteredConstructorIterator(includeDuplicates: true);