diff --git a/reflectable/CHANGELOG.md b/reflectable/CHANGELOG.md index fdfb1fe..6f3ba43 100644 --- a/reflectable/CHANGELOG.md +++ b/reflectable/CHANGELOG.md @@ -1,3 +1,8 @@ +## 4.0.13 + +* Update dependencies: `analyzer` 7.4, `build_runner` 2.4.15, + `dart_style` 3.0.0, `lints` 6.0.0. + ## 4.0.12 * Revert analyzer dependency to 6.8.0 and lints to 5.0.0 due to macro diff --git a/reflectable/lib/capability.dart b/reflectable/lib/capability.dart index 7442407..c09f8b9 100644 --- a/reflectable/lib/capability.dart +++ b/reflectable/lib/capability.dart @@ -337,8 +337,10 @@ const subtypeQuantifyCapability = _SubtypeQuantifyCapability(); class SuperclassQuantifyCapability implements ReflecteeQuantifyCapability { final Type upperBound; final bool excludeUpperBound; - const SuperclassQuantifyCapability(this.upperBound, - {this.excludeUpperBound = false}); + const SuperclassQuantifyCapability( + this.upperBound, { + this.excludeUpperBound = false, + }); } /// Gives support for reflection on all superclasses of covered classes. @@ -371,8 +373,9 @@ const typeAnnotationQuantifyCapability = TypeAnnotationQuantifyCapability(); /// the vocered classes, as well as the transitive closure thereof (that is, /// including classes used as type annotations in classes used as type /// annotations, etc.). -const typeAnnotationDeepQuantifyCapability = - TypeAnnotationQuantifyCapability(transitive: true); +const typeAnnotationDeepQuantifyCapability = TypeAnnotationQuantifyCapability( + transitive: true, +); /// Quantifying capability instance specifying that the reflection support /// for any given explicitly declared getter must also be given to its @@ -427,7 +430,7 @@ class ImportAttachedCapability { class GlobalQuantifyCapability extends ImportAttachedCapability { final String classNamePattern; const GlobalQuantifyCapability(this.classNamePattern, Reflectable reflector) - : super(reflector); + : super(reflector); } /// Gives reflection support in [reflector] for every class @@ -443,7 +446,7 @@ class GlobalQuantifyCapability extends ImportAttachedCapability { class GlobalQuantifyMetaCapability extends ImportAttachedCapability { final Type metadataType; const GlobalQuantifyMetaCapability(this.metadataType, Reflectable reflector) - : super(reflector); + : super(reflector); } // ---------- Private classes used to enable capability instances above. @@ -509,8 +512,12 @@ class _StringInvocation extends StringInvocation { @override bool get isSetter => kind == StringInvocationKind.setter; - _StringInvocation(this.memberName, this.positionalArguments, - this.namedArguments, this.kind); + _StringInvocation( + this.memberName, + this.positionalArguments, + this.namedArguments, + this.kind, + ); } /// Thrown when a method is invoked via a reflectable, but the reflectable @@ -533,11 +540,20 @@ class ReflectableNoSuchMethodError extends Error final StringInvocationKind kind; - ReflectableNoSuchMethodError(this.receiver, this.memberName, - this.positionalArguments, this.namedArguments, this.kind); + ReflectableNoSuchMethodError( + this.receiver, + this.memberName, + this.positionalArguments, + this.namedArguments, + this.kind, + ); StringInvocation get invocation => _StringInvocation( - memberName, positionalArguments, namedArguments ?? const {}, kind); + memberName, + positionalArguments, + namedArguments ?? const {}, + kind, + ); @override String toString() { @@ -555,7 +571,8 @@ class ReflectableNoSuchMethodError extends Error case StringInvocationKind.constructor: kindName = 'constructor'; } - var description = 'NoSuchCapabilityError: no capability to invoke the ' + var description = + 'NoSuchCapabilityError: no capability to invoke the ' '$kindName "$memberName"\n' 'Receiver: $receiver\n' 'Arguments: $positionalArguments\n'; @@ -567,38 +584,77 @@ class ReflectableNoSuchMethodError extends Error } dynamic reflectableNoSuchInvokableError( - Object? receiver, - String memberName, - List positionalArguments, - Map? namedArguments, - StringInvocationKind kind) { + Object? receiver, + String memberName, + List positionalArguments, + Map? namedArguments, + StringInvocationKind kind, +) { throw ReflectableNoSuchMethodError( - receiver, memberName, positionalArguments, namedArguments, kind); -} - -dynamic reflectableNoSuchMethodError(Object? receiver, String memberName, - List positionalArguments, Map? namedArguments) { - throw ReflectableNoSuchMethodError(receiver, memberName, positionalArguments, - namedArguments, StringInvocationKind.method); -} - -dynamic reflectableNoSuchGetterError(Object? receiver, String memberName, - List positionalArguments, Map? namedArguments) { - throw ReflectableNoSuchMethodError(receiver, memberName, positionalArguments, - namedArguments, StringInvocationKind.getter); -} - -dynamic reflectableNoSuchSetterError(Object? receiver, String memberName, - List positionalArguments, Map? namedArguments) { - throw ReflectableNoSuchMethodError(receiver, memberName, positionalArguments, - namedArguments, StringInvocationKind.setter); + receiver, + memberName, + positionalArguments, + namedArguments, + kind, + ); +} + +dynamic reflectableNoSuchMethodError( + Object? receiver, + String memberName, + List positionalArguments, + Map? namedArguments, +) { + throw ReflectableNoSuchMethodError( + receiver, + memberName, + positionalArguments, + namedArguments, + StringInvocationKind.method, + ); +} + +dynamic reflectableNoSuchGetterError( + Object? receiver, + String memberName, + List positionalArguments, + Map? namedArguments, +) { + throw ReflectableNoSuchMethodError( + receiver, + memberName, + positionalArguments, + namedArguments, + StringInvocationKind.getter, + ); +} + +dynamic reflectableNoSuchSetterError( + Object? receiver, + String memberName, + List positionalArguments, + Map? namedArguments, +) { + throw ReflectableNoSuchMethodError( + receiver, + memberName, + positionalArguments, + namedArguments, + StringInvocationKind.setter, + ); } dynamic reflectableNoSuchConstructorError( - Object? receiver, - String constructorName, - List positionalArguments, - Map? namedArguments) { - throw ReflectableNoSuchMethodError(receiver, constructorName, - positionalArguments, namedArguments, StringInvocationKind.constructor); + Object? receiver, + String constructorName, + List positionalArguments, + Map? namedArguments, +) { + throw ReflectableNoSuchMethodError( + receiver, + constructorName, + positionalArguments, + namedArguments, + StringInvocationKind.constructor, + ); } diff --git a/reflectable/lib/mirrors.dart b/reflectable/lib/mirrors.dart index 4adb2e6..1e75afc 100644 --- a/reflectable/lib/mirrors.dart +++ b/reflectable/lib/mirrors.dart @@ -337,8 +337,11 @@ abstract class ObjectMirror implements Mirror { /// [StaticInvokeMetaCapability]; and [invoke] on a top-level function /// requires a matching [TopLevelInvokeCapability] or /// [TopLevelInvokeMetaCapability]. - Object? invoke(String memberName, List positionalArguments, - [Map? namedArguments]); // RET: InstanceMirror + Object? invoke( + String memberName, + List positionalArguments, [ + Map? namedArguments, + ]); // RET: InstanceMirror /// Invokes a getter and returns the result. The getter can be the /// implicit getter for a field, or a user-defined getter method. @@ -540,8 +543,10 @@ abstract class ClosureMirror implements InstanceMirror { /// Required capabilities: [apply] requires a matching /// [InstanceInvokeCapability] or [InstanceInvokeMetaCapability], targeting /// the relevant `call` method. - Object? apply(List positionalArguments, - [Map? namedArguments]); // RET: InstanceMirror + Object? apply( + List positionalArguments, [ + Map? namedArguments, + ]); // RET: InstanceMirror } /// A [LibraryMirror] reflects a Dart language library, providing @@ -965,8 +970,11 @@ abstract class ClassMirror implements TypeMirror, ObjectMirror { /// /// Required capabilities: [newInstance] requires a matching /// [NewInstanceCapability] or [NewInstanceMetaCapability]. - Object newInstance(String constructorName, List positionalArguments, - [Map namedArguments]); // RET: InstanceMirror + Object newInstance( + String constructorName, + List positionalArguments, [ + Map namedArguments, + ]); // RET: InstanceMirror /// Whether this mirror is equal to [other]. /// diff --git a/reflectable/lib/reflectable.dart b/reflectable/lib/reflectable.dart index 57fae66..de0f4ca 100644 --- a/reflectable/lib/reflectable.dart +++ b/reflectable/lib/reflectable.dart @@ -114,17 +114,18 @@ abstract class Reflectable extends implementation.ReflectableImpl /// Const constructor, to enable usage as metadata, allowing for varargs /// style invocation with up to ten arguments. - const Reflectable( - [super.cap0, - super.cap1, - super.cap2, - super.cap3, - super.cap4, - super.cap5, - super.cap6, - super.cap7, - super.cap8, - super.cap9]); + const Reflectable([ + super.cap0, + super.cap1, + super.cap2, + super.cap3, + super.cap4, + super.cap5, + super.cap6, + super.cap7, + super.cap8, + super.cap9, + ]); const Reflectable.fromList(super.capabilities) : super.fromList(); diff --git a/reflectable/lib/reflectable_builder.dart b/reflectable/lib/reflectable_builder.dart index 379ed0d..0bcab02 100644 --- a/reflectable/lib/reflectable_builder.dart +++ b/reflectable/lib/reflectable_builder.dart @@ -30,14 +30,21 @@ class ReflectableBuilder implements Builder { AssetId outputId = inputId.changeExtension('.reflectable.dart'); List visibleLibraries = await resolver.libraries.toList(); String generatedSource = await BuilderImplementation().buildMirrorLibrary( - resolver, inputId, outputId, inputLibrary, visibleLibraries, true, []); + resolver, + inputId, + outputId, + inputLibrary, + visibleLibraries, + true, + [], + ); await buildStep.writeAsString(outputId, generatedSource); } @override Map> get buildExtensions => const { - '.dart': ['.reflectable.dart'] - }; + '.dart': ['.reflectable.dart'], + }; } ReflectableBuilder reflectableBuilder(BuilderOptions options) { @@ -55,12 +62,13 @@ Future reflectableBuild(List arguments) async { } else { // TODO(eernst) feature: We should support some customization of // the settings, e.g., specifying options like `suppress_warnings`. - var options = BuilderOptions( - {'entry_points': arguments, 'formatted': true}, - isRoot: true); + var options = BuilderOptions({ + 'entry_points': arguments, + 'formatted': true, + }, isRoot: true); final builder = ReflectableBuilder(options); var builders = [ - applyToRoot(builder, generateFor: InputSet(include: arguments)) + applyToRoot(builder, generateFor: InputSet(include: arguments)), ]; PackageGraph packageGraph = await PackageGraph.forThisPackage(); var environment = OverrideableEnvironment(IOEnvironment(packageGraph)); @@ -71,8 +79,12 @@ Future reflectableBuild(List arguments) async { ); try { BuildRunner build = await BuildRunner.create( - buildOptions, environment, builders, const {}, - isReleaseBuild: false); + buildOptions, + environment, + builders, + const {}, + isReleaseBuild: false, + ); BuildResult result = await build.run(const {}); await build.beforeExit(); return result; diff --git a/reflectable/lib/src/builder_implementation.dart b/reflectable/lib/src/builder_implementation.dart index 923bf32..c84a606 100644 --- a/reflectable/lib/src/builder_implementation.dart +++ b/reflectable/lib/src/builder_implementation.dart @@ -12,7 +12,7 @@ import 'package:analyzer/dart/analysis/session.dart'; import 'package:analyzer/dart/analysis/results.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/constant/value.dart'; -import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/element2.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/dart/element/type_system.dart'; @@ -21,16 +21,17 @@ import 'package:analyzer/error/listener.dart'; import 'package:analyzer/source/line_info.dart'; import 'package:analyzer/source/source.dart'; import 'package:analyzer/source/file_source.dart'; -import 'package:analyzer/src/dart/constant/compute.dart'; -import 'package:analyzer/src/dart/constant/evaluation.dart'; -import 'package:analyzer/src/dart/constant/utilities.dart'; -import 'package:analyzer/src/dart/constant/value.dart'; -import 'package:analyzer/src/dart/element/element.dart'; -import 'package:analyzer/src/dart/element/type.dart'; -import 'package:analyzer/src/summary/package_bundle_reader.dart'; +//import 'package:analyzer/src/dart/constant/compute.dart'; +//import 'package:analyzer/src/dart/constant/evaluation.dart'; +//import 'package:analyzer/src/dart/constant/utilities.dart'; +//import 'package:analyzer/src/dart/constant/value.dart'; +//import 'package:analyzer/src/dart/element/element.dart'; +//import 'package:analyzer/src/dart/element/type.dart'; +//import 'package:analyzer/src/summary/package_bundle_reader.dart'; import 'package:build/build.dart'; import 'package:dart_style/dart_style.dart'; import 'package:path/path.dart' as path; +import 'package:pub_semver/pub_semver.dart'; import 'element_capability.dart' as ec; import 'encoding_constants.dart' as constants; import 'fixed_point.dart'; @@ -38,6 +39,16 @@ import 'incompleteness.dart'; import 'reflectable_class_constants.dart' as reflectable_class_constants; import 'reflectable_errors.dart' as errors; +// !!!MIGRATION!!! + +extension on InterfaceElement2 { + dynamic get typeParameters => throw "!!!TODO!!!"; +} + +extension on SetterElement { + dynamic get correspondingGetter => throw "!!!TODO!!!"; +} + // ignore_for_file: omit_local_variable_types /// Specifiers for warnings that may be suppressed; `allWarnings` disables all @@ -51,16 +62,16 @@ enum WarningKind { badMetadata, badReflectorClass, unrecognizedReflector, - unusedReflector + unusedReflector, } class _ReflectionWorld { final Resolver resolver; - final List libraries; + final List libraries; final AssetId generatedLibraryId; final List<_ReflectorDomain> reflectors; - final LibraryElement reflectableLibrary; - final LibraryElement entryPointLibrary; + final LibraryElement2 reflectableLibrary; + final LibraryElement2 entryPointLibrary; final _ImportCollector importCollector; /// Used to collect the names of covered members during `generateCode`, then @@ -69,57 +80,66 @@ class _ReflectionWorld { final Set memberNames = {}; _ReflectionWorld( - this.resolver, - this.libraries, - this.generatedLibraryId, - this.reflectors, - this.reflectableLibrary, - this.entryPointLibrary, - this.importCollector); + this.resolver, + this.libraries, + this.generatedLibraryId, + this.reflectors, + this.reflectableLibrary, + this.entryPointLibrary, + this.importCollector, + ); /// The inverse relation of `superinterfaces` union `superclass`, globally. - Map> get subtypes { + Map> get subtypes { if (_subtypesCache != null) return _subtypesCache!; // Initialize [_subtypesCache], ready to be filled in. - var subtypes = >{}; + var subtypes = >{}; void addSubtypeRelation( - InterfaceElement supertype, InterfaceElement subtype) { - Set? subtypesOfSupertype = subtypes[supertype]; + InterfaceElement2 supertype, + InterfaceElement2 subtype, + ) { + Set? subtypesOfSupertype = subtypes[supertype]; if (subtypesOfSupertype == null) { - subtypesOfSupertype = {}; + subtypesOfSupertype = {}; subtypes[supertype] = subtypesOfSupertype; } subtypesOfSupertype.add(subtype); } // Fill in [_subtypesCache]. - for (LibraryElement library in libraries) { - void addInterfaceElement(InterfaceElement interfaceElement) { + for (LibraryElement2 library in libraries) { + void addInterfaceElement(InterfaceElement2 interfaceElement) { InterfaceType? supertype = interfaceElement.supertype; if (interfaceElement.mixins.isEmpty) { - InterfaceElement? supertypeElement = supertype?.element; + InterfaceElement2? supertypeElement = supertype?.element3; if (supertypeElement != null) { addSubtypeRelation(supertypeElement, interfaceElement); } } else { // Mixins must be applied to a superclass, so it is not null. - InterfaceElement superclass = supertype!.element; + InterfaceElement2 superclass = supertype!.element3; // Iterate over all mixins in most-general-first order (so with // `class C extends B with M1, M2..` we visit `M1` then `M2`. for (InterfaceType mixin in interfaceElement.mixins) { - InterfaceElement mixinElement = mixin.element; - InterfaceElement? subClass = + InterfaceElement2 mixinElement = mixin.element3; + InterfaceElement2? subClass = mixin == interfaceElement.mixins.last ? interfaceElement : null; - String? name = subClass == null - ? null - : (interfaceElement is MixinApplication && - interfaceElement.isMixinApplication - ? interfaceElement.name - : null); + String? name = + subClass == null + ? null + : (interfaceElement is MixinApplication && + interfaceElement.isMixinApplication + ? interfaceElement.name3 + : null); var mixinApplication = MixinApplication( - name, superclass, mixinElement, library, subClass); + name, + superclass, + mixinElement, + library, + subClass, + ); addSubtypeRelation(superclass, mixinApplication); addSubtypeRelation(mixinElement, mixinApplication); if (subClass != null) { @@ -129,24 +149,24 @@ class _ReflectionWorld { } } for (InterfaceType type in interfaceElement.interfaces) { - addSubtypeRelation(type.element, interfaceElement); + addSubtypeRelation(type.element3, interfaceElement); } } - for (CompilationUnitElement unit in library.units) { - for (ClassElement interfaceElement in unit.classes) { - addInterfaceElement(interfaceElement); + for (LibraryFragment fragment in library.fragments) { + for (ClassFragment classFragment in fragment.classes2) { + addInterfaceElement(classFragment.element); } - for (EnumElement interfaceElement in unit.enums) { - addInterfaceElement(interfaceElement); + for (EnumFragment enumFragment in fragment.enums2) { + addInterfaceElement(enumFragment.element); } } } return _subtypesCache = - Map>.unmodifiable(subtypes); + Map>.unmodifiable(subtypes); } - Map>? _subtypesCache; + Map>? _subtypesCache; /// Returns code which will create all the data structures (esp. mirrors) /// needed to enable the correct behavior for all [reflectors]. @@ -156,21 +176,29 @@ class _ReflectionWorld { var typedefsCode = '\n'; var reflectorsCode = []; for (_ReflectorDomain reflector in reflectors) { - String reflectorCode = - await reflector._generateCode(this, importCollector, typedefs); + String reflectorCode = await reflector._generateCode( + this, + importCollector, + typedefs, + ); if (typedefs.isNotEmpty) { for (DartType dartType in typedefs.keys) { String body = await reflector._typeCodeOfTypeArgument( - dartType, importCollector, typeVariablesInScope, typedefs, - useNameOfGenericFunctionType: false); + dartType, + importCollector, + typeVariablesInScope, + typedefs, + useNameOfGenericFunctionType: false, + ); typedefsCode += '\ntypedef ${_typedefName(typedefs[dartType]!)} = $body;'; } typedefs.clear(); } - reflectorsCode - .add('${await reflector._constConstructionCode(importCollector)}: ' - '$reflectorCode'); + reflectorsCode.add( + '${await reflector._constConstructionCode(importCollector)}: ' + '$reflectorCode', + ); } return 'final _data = ' '${_formatAsMap(reflectorsCode)};$typedefsCode'; @@ -181,11 +209,14 @@ class _ReflectionWorld { /// is collected during the execution of `generateCode`, which means that /// this method must be called after `generateCode`. String generateSymbolMap() { - if (reflectors.any((_ReflectorDomain reflector) => - reflector._capabilities._impliesMemberSymbols)) { + if (reflectors.any( + (_ReflectorDomain reflector) => + reflector._capabilities._impliesMemberSymbols, + )) { // Generate the mapping when requested, even if it is empty. String mapping = _formatAsMap( - memberNames.map((String name) => "const Symbol(r'$name'): r'$name'")); + memberNames.map((String name) => "const Symbol(r'$name'): r'$name'"), + ); return mapping; } else { // The value `null` unambiguously indicates lack of capability. @@ -230,17 +261,17 @@ class Enumerator { } } -/// Hybrid data structure holding [InterfaceElement]s and supporting data. +/// Hybrid data structure holding [InterfaceElement2]s and supporting data. /// It holds three different data structures used to describe the set of /// classes under transformation. It holds an [Enumerator] named /// [interfaceElements] which is a set-like data structure that also enables /// clients to obtain unique indices for each member; it holds a map -/// [elementToDomain] that maps each [InterfaceElement] to a corresponding +/// [elementToDomain] that maps each [InterfaceElement2] to a corresponding /// [_ClassDomain]; and it holds a relation [mixinApplicationSupers] that -/// maps each [InterfaceElement] which is a direct subclass of a mixin +/// maps each [InterfaceElement2] which is a direct subclass of a mixin /// application to its superclass. The latter is needed because the analyzer /// representation of mixins and mixin applications makes it difficult to find -/// a superclass which is a mixin application (`InterfaceElement.supertype` is +/// a superclass which is a mixin application (`InterfaceElement2.supertype` is /// the _syntactic_ superclass, that is, for `class C extends B with M..` it /// is `B`, not the mixin application `B with M`). The three data structures /// are bundled together in this class because they must remain consistent and @@ -249,14 +280,14 @@ class Enumerator { /// operations to the [interfaceElements], because they will not break /// consistency, but for every mutating method we need to maintain the /// invariants. -class _InterfaceElementEnhancedSet implements Set { +class _InterfaceElementEnhancedSet implements Set { final _ReflectorDomain reflectorDomain; - final Enumerator interfaceElements = - Enumerator(); - final Map elementToDomain = - {}; - final Map mixinApplicationSupers = - {}; + final Enumerator interfaceElements = + Enumerator(); + final Map elementToDomain = + {}; + final Map mixinApplicationSupers = + {}; bool _unmodifiable = false; _InterfaceElementEnhancedSet(this.reflectorDomain); @@ -270,17 +301,17 @@ class _InterfaceElementEnhancedSet implements Set { } @override - Iterable map(T Function(InterfaceElement) f) => + Iterable map(T Function(InterfaceElement2) f) => interfaceElements.items.map(f); @override Set cast() { Iterable self = this; - return self is Set ? self : Set.castFrom(this); + return self is Set ? self : Set.castFrom(this); } @override - Iterable where(bool Function(InterfaceElement) f) { + Iterable where(bool Function(InterfaceElement2) f) { return interfaceElements.items.where(f); } @@ -294,27 +325,28 @@ class _InterfaceElementEnhancedSet implements Set { } @override - Iterable expand(Iterable Function(InterfaceElement) f) { + Iterable expand(Iterable Function(InterfaceElement2) f) { return interfaceElements.items.expand(f); } @override - void forEach(void Function(InterfaceElement) f) => + void forEach(void Function(InterfaceElement2) f) => interfaceElements.items.forEach(f); @override - InterfaceElement reduce( - InterfaceElement Function(InterfaceElement, InterfaceElement) combine) { + InterfaceElement2 reduce( + InterfaceElement2 Function(InterfaceElement2, InterfaceElement2) combine, + ) { return interfaceElements.items.reduce(combine); } @override - T fold(T initialValue, T Function(T, InterfaceElement) combine) { + T fold(T initialValue, T Function(T, InterfaceElement2) combine) { return interfaceElements.items.fold(initialValue, combine); } @override - bool every(bool Function(InterfaceElement) f) => + bool every(bool Function(InterfaceElement2) f) => interfaceElements.items.every(f); @override @@ -322,10 +354,11 @@ class _InterfaceElementEnhancedSet implements Set { interfaceElements.items.join(separator); @override - bool any(bool Function(InterfaceElement) f) => interfaceElements.items.any(f); + bool any(bool Function(InterfaceElement2) f) => + interfaceElements.items.any(f); @override - List toList({bool growable = true}) { + List toList({bool growable = true}) { return interfaceElements.items.toList(growable: growable); } @@ -339,76 +372,83 @@ class _InterfaceElementEnhancedSet implements Set { bool get isNotEmpty => interfaceElements.items.isNotEmpty; @override - Iterable take(int count) => + Iterable take(int count) => interfaceElements.items.take(count); @override - Iterable takeWhile(bool Function(InterfaceElement) test) { + Iterable takeWhile(bool Function(InterfaceElement2) test) { return interfaceElements.items.takeWhile(test); } @override - Iterable skip(int count) => + Iterable skip(int count) => interfaceElements.items.skip(count); @override - Iterable skipWhile(bool Function(InterfaceElement) test) { + Iterable skipWhile(bool Function(InterfaceElement2) test) { return interfaceElements.items.skipWhile(test); } @override - Iterable followedBy( - Iterable other) sync* { + Iterable followedBy( + Iterable other, + ) sync* { yield* this; yield* other; } @override - InterfaceElement get first => interfaceElements.items.first; + InterfaceElement2 get first => interfaceElements.items.first; @override - InterfaceElement get last => interfaceElements.items.last; + InterfaceElement2 get last => interfaceElements.items.last; @override - InterfaceElement get single => interfaceElements.items.single; + InterfaceElement2 get single => interfaceElements.items.single; @override - InterfaceElement firstWhere(bool Function(InterfaceElement) test, - {InterfaceElement Function()? orElse}) { + InterfaceElement2 firstWhere( + bool Function(InterfaceElement2) test, { + InterfaceElement2 Function()? orElse, + }) { return interfaceElements.items.firstWhere(test, orElse: orElse); } @override - InterfaceElement lastWhere(bool Function(InterfaceElement) test, - {InterfaceElement Function()? orElse}) { + InterfaceElement2 lastWhere( + bool Function(InterfaceElement2) test, { + InterfaceElement2 Function()? orElse, + }) { return interfaceElements.items.lastWhere(test, orElse: orElse); } @override - InterfaceElement singleWhere(bool Function(InterfaceElement) test, - {InterfaceElement Function()? orElse}) { + InterfaceElement2 singleWhere( + bool Function(InterfaceElement2) test, { + InterfaceElement2 Function()? orElse, + }) { return interfaceElements.items.singleWhere(test); } @override - InterfaceElement elementAt(int index) => + InterfaceElement2 elementAt(int index) => interfaceElements.items.elementAt(index); @override - Iterator get iterator => interfaceElements.items.iterator; + Iterator get iterator => interfaceElements.items.iterator; @override bool contains(Object? value) => interfaceElements.items.contains(value); @override - bool add(InterfaceElement value) { + bool add(InterfaceElement2 value) { assert(!_unmodifiable); bool result = interfaceElements.add(value); if (result) { assert(!elementToDomain.containsKey(value)); elementToDomain[value] = _createClassDomain(value, reflectorDomain); if (value is MixinApplication) { - InterfaceElement? valueSubclass = value.subclass; + InterfaceElement2? valueSubclass = value.subclass; if (valueSubclass != null) { // [value] is a mixin application which is the immediate superclass // of a class which is a regular class (not a mixin application). This @@ -423,7 +463,7 @@ class _InterfaceElementEnhancedSet implements Set { } @override - void addAll(Iterable elements) => elements.forEach(add); + void addAll(Iterable elements) => elements.forEach(add); @override bool remove(Object? value) { @@ -444,8 +484,8 @@ class _InterfaceElementEnhancedSet implements Set { } @override - InterfaceElement? lookup(Object? object) { - for (InterfaceElement classElement in interfaceElements._map.keys) { + InterfaceElement2? lookup(Object? object) { + for (InterfaceElement2 classElement in interfaceElements._map.keys) { if (object == classElement) return classElement; } return null; @@ -456,22 +496,22 @@ class _InterfaceElementEnhancedSet implements Set { @override void retainAll(Iterable elements) { - bool test(InterfaceElement element) => !elements.contains(element); + bool test(InterfaceElement2 element) => !elements.contains(element); removeWhere(test); } @override - void removeWhere(bool Function(InterfaceElement) test) { - var toRemove = {}; - for (InterfaceElement classElement in interfaceElements.items) { + void removeWhere(bool Function(InterfaceElement2) test) { + var toRemove = {}; + for (InterfaceElement2 classElement in interfaceElements.items) { if (test(classElement)) toRemove.add(classElement); } removeAll(toRemove); } @override - void retainWhere(bool Function(InterfaceElement) test) { - bool invertedTest(InterfaceElement element) => !test(element); + void retainWhere(bool Function(InterfaceElement2) test) { + bool invertedTest(InterfaceElement2 element) => !test(element); removeWhere(invertedTest); } @@ -481,17 +521,17 @@ class _InterfaceElementEnhancedSet implements Set { } @override - Set intersection(Set other) { + Set intersection(Set other) { return interfaceElements.items.toSet().intersection(other); } @override - Set union(Set other) { + Set union(Set other) { return interfaceElements.items.toSet().union(other); } @override - Set difference(Set other) { + Set difference(Set other) { return interfaceElements.items.toSet().difference(other); } @@ -503,7 +543,7 @@ class _InterfaceElementEnhancedSet implements Set { } @override - Set toSet() => this; + Set toSet() => this; /// Returns the superclass of the given [classElement] using the language /// semantics rather than the analyzer model (where the superclass is the @@ -512,7 +552,7 @@ class _InterfaceElementEnhancedSet implements Set { /// data to find the superclass, which means that it will _not_ refrain /// from returning a class which is not covered by any particular reflector. /// It is up to the caller to check that. - InterfaceElement? superclassOf(InterfaceElement classElement) { + InterfaceElement2? superclassOf(InterfaceElement2 classElement) { // By construction of [MixinApplication]s, their `superclass` is correct. if (classElement is MixinApplication) return classElement.superclass; // For a regular class whose superclass is also not a mixin application, @@ -522,7 +562,7 @@ class _InterfaceElementEnhancedSet implements Set { // returning [null] to indicate that a superclass is not covered, because // this method does not check coverage. if (classElement.mixins.isEmpty) { - return classElement.supertype?.element; + return classElement.supertype?.element3; } // [classElement] is now known to be a regular class whose superclass // is a mixin application. For each [MixinApplication] `m` we store, if it @@ -535,7 +575,7 @@ class _InterfaceElementEnhancedSet implements Set { /// Returns the _ClassDomain corresponding to the given [classElement], /// which must be a member of this [_InterfaceElementEnhancedSet]. - _ClassDomain domainOf(InterfaceElement classElement) { + _ClassDomain domainOf(InterfaceElement2 classElement) { assert(elementToDomain.containsKey(classElement)); return elementToDomain[classElement]!; } @@ -580,18 +620,23 @@ class ParameterListShape { final int numberOfOptionalPositionalParameters; final Set namesOfNamedParameters; - const ParameterListShape(this.numberOfPositionalParameters, - this.numberOfOptionalPositionalParameters, this.namesOfNamedParameters); + const ParameterListShape( + this.numberOfPositionalParameters, + this.numberOfOptionalPositionalParameters, + this.namesOfNamedParameters, + ); @override - bool operator ==(other) => other is ParameterListShape - ? numberOfPositionalParameters == other.numberOfPositionalParameters && - numberOfOptionalPositionalParameters == - other.numberOfOptionalPositionalParameters && - namesOfNamedParameters - .difference(other.namesOfNamedParameters) - .isEmpty - : false; + bool operator ==(other) => + other is ParameterListShape + ? numberOfPositionalParameters == + other.numberOfPositionalParameters && + numberOfOptionalPositionalParameters == + other.numberOfOptionalPositionalParameters && + namesOfNamedParameters + .difference(other.namesOfNamedParameters) + .isEmpty + : false; @override int get hashCode => @@ -619,7 +664,7 @@ class _ReflectorDomain { late final _ReflectionWorld _world; final Resolver _resolver; final AssetId _generatedLibraryId; - final InterfaceElement _reflector; + final InterfaceElement2 _reflector; /// Do not use this, use [classes] which ensures that closure operations /// have been performed as requested in [_capabilities]. Exception: In @@ -643,9 +688,10 @@ class _ReflectorDomain { await _SubtypesFixedPoint(_world.subtypes).expand(_classes); } if (_capabilities._impliesUpwardsClosure) { - await _SuperclassFixedPoint(await _capabilities._upwardsClosureBounds, - _capabilities._impliesMixins) - .expand(_classes); + await _SuperclassFixedPoint( + await _capabilities._upwardsClosureBounds, + _capabilities._impliesMixins, + ).expand(_classes); } else { // Even without an upwards closure we cover some superclasses, namely // mixin applications where the class applied as a mixin is covered (it @@ -657,7 +703,10 @@ class _ReflectorDomain { if (_capabilities._impliesTypes && _capabilities._impliesTypeAnnotations) { var fix = _AnnotationClassFixedPoint( - _resolver, _generatedLibraryId, _classes.domainOf); + _resolver, + _generatedLibraryId, + _classes.domainOf, + ); if (_capabilities._impliesTypeAnnotationClosure) { await fix.expand(_classes); } else { @@ -669,17 +718,21 @@ class _ReflectorDomain { return _classes; } - final Enumerator _libraries = Enumerator(); + final Enumerator _libraries = Enumerator(); final _Capabilities _capabilities; - _ReflectorDomain(this._resolver, this._generatedLibraryId, this._reflector, - this._capabilities) { + _ReflectorDomain( + this._resolver, + this._generatedLibraryId, + this._reflector, + this._capabilities, + ) { _classes = _InterfaceElementEnhancedSet(this); } final _instanceMemberCache = - >{}; + >{}; /// Returns a string that evaluates to a closure invoking [constructor] with /// the given arguments. @@ -691,15 +744,18 @@ class _ReflectorDomain { /// returns "(x, {y: 3}) => prefix1.Foo(x, y)", and records an import of /// the library of `Foo` associated with prefix1 in [importCollector]. Future _constructorCode( - ConstructorElement constructor, _ImportCollector importCollector) async { + ConstructorElement2 constructor, + _ImportCollector importCollector, + ) async { FunctionType type = constructor.type; int requiredPositionalCount = type.normalParameterTypes.length; int optionalPositionalCount = type.optionalParameterTypes.length; - List parameterNames = type.parameters - .map((ParameterElement parameter) => parameter.name) - .toList(); + List parameterNames = + type.formalParameters + .map((FormalParameterElement parameter) => parameter.name3!) + .toList(); List namedParameterNames = type.namedParameterTypes.keys.toList(); @@ -720,24 +776,28 @@ class _ReflectorDomain { // argument (say, "Hello, world!") and then test for that value, but that // would suppress an error in a very-hard-to-explain case, so that's safer // in a sense, but too weird. - if (constructor.library.isDartCore && - constructor.enclosingElement.name == 'List' && - constructor.name == '') { + if (constructor.library2.isDartCore && + constructor.enclosingElement2.name3 == 'List' && + constructor.name3 == '') { return '(bool b) => ([length]) => ' 'b ? (length == null ? [] : List.filled(length, null)) : null'; } - String positionals = - Iterable.generate(requiredPositionalCount, (int i) => parameterNames[i]) - .join(', '); + String positionals = Iterable.generate( + requiredPositionalCount, + (int i) => parameterNames[i], + ).join(', '); var optionalsWithDefaultList = []; for (var i = 0; i < optionalPositionalCount; i++) { String code = await _extractDefaultValueCode( - importCollector, constructor.parameters[requiredPositionalCount + i]); + importCollector, + constructor.formalParameters[requiredPositionalCount + i], + ); var defaultPart = code.isEmpty ? '' : ' = $code'; - optionalsWithDefaultList - .add('${parameterNames[requiredPositionalCount + i]}$defaultPart'); + optionalsWithDefaultList.add( + '${parameterNames[requiredPositionalCount + i]}$defaultPart', + ); } String optionalsWithDefaults = optionalsWithDefaultList.join(', '); @@ -747,19 +807,24 @@ class _ReflectorDomain { // on a language design where no parameter list can include // both optional positional and named parameters, so if there are // any named parameters then all optional parameters are named. - ParameterElement parameterElement = - constructor.parameters[requiredPositionalCount + i]; - String code = - await _extractDefaultValueCode(importCollector, parameterElement); + FormalParameterElement parameterElement = + constructor.formalParameters[requiredPositionalCount + i]; + String code = await _extractDefaultValueCode( + importCollector, + parameterElement, + ); var defaultPart = code.isEmpty ? '' : ' = $code'; - namedWithDefaultList.add('${parameterElement.name}$defaultPart'); + namedWithDefaultList.add('${parameterElement.name3}$defaultPart'); } String namedWithDefaults = namedWithDefaultList.join(', '); - String optionalArguments = Iterable.generate(optionalPositionalCount, - (int i) => parameterNames[i + requiredPositionalCount]).join(', '); - String namedArguments = - namedParameterNames.map((String name) => '$name: $name').join(', '); + String optionalArguments = Iterable.generate( + optionalPositionalCount, + (int i) => parameterNames[i + requiredPositionalCount], + ).join(', '); + String namedArguments = namedParameterNames + .map((String name) => '$name: $name') + .join(', '); var parameterParts = []; var argumentParts = []; @@ -782,7 +847,7 @@ class _ReflectorDomain { doRunArgument = '${doRunArgument}b'; } - String prefix = importCollector._getPrefix(constructor.library); + String prefix = importCollector._getPrefix(constructor.library2); return ('(bool $doRunArgument) => (${parameterParts.join(', ')}) => ' '$doRunArgument ? $prefix${await _nameOfConstructor(constructor)}' '(${argumentParts.join(', ')}) : null'); @@ -790,47 +855,53 @@ class _ReflectorDomain { /// The code of the const-construction of this reflector. Future _constConstructionCode( - _ImportCollector importCollector) async { - String prefix = importCollector._getPrefix(_reflector.library); - if (_isPrivateName(_reflector.name)) { + _ImportCollector importCollector, + ) async { + String prefix = importCollector._getPrefix(_reflector.library2); + if (_isPrivateName(_reflector.name3!)) { await _severe( - 'Cannot access private name `${_reflector.name}`', _reflector); + 'Cannot access private name `${_reflector.name3}`', + _reflector, + ); } - return 'const $prefix${_reflector.name}()'; + return 'const $prefix${_reflector.name3}()'; } /// Generate the code which will create a `ReflectorData` instance /// containing the mirrors and other reflection data which is needed for /// `_reflector` to behave correctly. - Future _generateCode(_ReflectionWorld world, - _ImportCollector importCollector, Map typedefs) async { + Future _generateCode( + _ReflectionWorld world, + _ImportCollector importCollector, + Map typedefs, + ) async { // Library related collections. var libraries = Enumerator<_LibraryDomain>(); - var libraryMap = {}; - var topLevelVariables = Enumerator(); + var libraryMap = {}; + var topLevelVariables = Enumerator(); // Class related collections. - var fields = Enumerator(); - var typeParameters = Enumerator(); + var fields = Enumerator(); + var typeParameters = Enumerator(); // Reflected types not in `classes`; appended to `ReflectorData.types`. var reflectedTypes = Enumerator(); var instanceGetterNames = {}; var instanceSetterNames = {}; // Library and class related collections. - var members = Enumerator(); - var parameters = Enumerator(); + var members = Enumerator(); + var parameters = Enumerator(); var parameterListShapes = Enumerator(); - var parameterListShapeOf = {}; + var parameterListShapeOf = {}; // Class element for [Object], needed as implicit upper bound. Initialized // if needed. - InterfaceElement? objectInterfaceElement; + InterfaceElement2? objectInterfaceElement; /// Adds a library domain for [library] to [libraries], relying on checks /// for importability and insertion into [importCollector] to have taken /// place already. - void uncheckedAddLibrary(LibraryElement library) { + void uncheckedAddLibrary(LibraryElement2 library) { _LibraryDomain libraryDomain = _createLibraryDomain(library, this); libraries.add(libraryDomain); libraryMap[library] = libraryDomain; @@ -841,9 +912,12 @@ class _ReflectorDomain { /// Used to add a library domain for [library] to [libraries], checking /// that it is importable and registering it with [importCollector]. - Future addLibrary(LibraryElement library) async { + Future addLibrary(LibraryElement2 library) async { if (!await _isImportableLibrary( - library, _generatedLibraryId, _resolver)) { + library, + _generatedLibraryId, + _resolver, + )) { return; } importCollector._addLibrary(library); @@ -853,10 +927,12 @@ class _ReflectorDomain { // Fill in [libraries], [typeParameters], [members], [fields], // [parameters], [instanceGetterNames], and [instanceSetterNames]. _libraries.items.forEach(uncheckedAddLibrary); - for (InterfaceElement classElement in await classes) { - LibraryElement classLibrary = classElement.library; - if (!libraries.items.any((_LibraryDomain libraryDomain) => - libraryDomain._libraryElement == classLibrary)) { + for (InterfaceElement2 classElement in await classes) { + LibraryElement2 classLibrary = classElement.library2; + if (!libraries.items.any( + (_LibraryDomain libraryDomain) => + libraryDomain._libraryElement == classLibrary, + )) { addLibrary(classLibrary); } classElement.typeParameters.forEach(typeParameters.add); @@ -890,18 +966,19 @@ class _ReflectorDomain { // Ensure that we include variables corresponding to the implicit // accessors that we have included into `members`. - for (ExecutableElement element in members.items) { - if (element is PropertyAccessorElement && element.isSynthetic) { - PropertyInducingElement? variable = element.variable2; - if (variable is FieldElement) { + for (ExecutableElement2 element in members.items) { + if (element is GetterElement && element.isSynthetic) { + PropertyInducingElement2? variable = element.variable3; + if (variable is FieldElement2) { fields.add(variable); - } else if (variable is TopLevelVariableElement) { + } else if (variable is TopLevelVariableElement2) { topLevelVariables.add(variable); } else { await _severe( - 'This kind of variable is not yet supported' - ' (${variable.runtimeType})', - variable); + 'This kind of variable is not yet supported' + ' (${variable.runtimeType})', + variable, + ); } } } @@ -910,18 +987,17 @@ class _ReflectorDomain { // including both explicitly declared ones, implicitly generated ones // for fields, and the implicitly generated ones that correspond to // method tear-offs. - for (ExecutableElement instanceMember in classDomain._instanceMembers) { - if (instanceMember is PropertyAccessorElement) { - // A getter or a setter, synthetic or declared. - if (instanceMember.isGetter) { - instanceGetterNames.add(instanceMember.name); - } else { - instanceSetterNames.add(instanceMember.name); - } - } else if (instanceMember is MethodElement) { - instanceGetterNames.add(instanceMember.name); + for (ExecutableElement2 instanceMember in classDomain._instanceMembers) { + if (instanceMember is GetterElement) { + // A getter, synthetic or declared. + instanceGetterNames.add(instanceMember.name3!); + } else if (instanceMember is SetterElement) { + // A setter, synthetic or declared. + instanceSetterNames.add(instanceMember.name3!); + } else if (instanceMember is MethodElement2) { + instanceGetterNames.add(instanceMember.name3!); } else { - // `instanceMember` is a ConstructorElement. + // `instanceMember` is a ConstructorElement2. // Even though a generative constructor has a false // `isStatic`, we do not wish to include them among // instanceGetterNames, so we do nothing here. @@ -931,27 +1007,28 @@ class _ReflectorDomain { // Add classes used as bounds for type variables, if needed. if (_capabilities._impliesTypes && _capabilities._impliesTypeAnnotations) { - Future addClass(InterfaceElement classElement) async { + Future addClass(InterfaceElement2 classElement) async { (await classes).add(classElement); - LibraryElement classLibrary = classElement.library; - if (!libraries.items - .any((domain) => domain._libraryElement == classLibrary)) { + LibraryElement2 classLibrary = classElement.library2; + if (!libraries.items.any( + (domain) => domain._libraryElement == classLibrary, + )) { uncheckedAddLibrary(classLibrary); } } var hasObject = false; var mustHaveObject = false; - var classesToAdd = {}; - InterfaceElement? anyInterfaceElement; - for (InterfaceElement classElement in await classes) { + var classesToAdd = {}; + InterfaceElement2? anyInterfaceElement; + for (InterfaceElement2 classElement in await classes) { if (_typeForReflectable(classElement).isDartCoreObject) { hasObject = true; objectInterfaceElement = classElement; break; } if (classElement.typeParameters.isNotEmpty) { - for (TypeParameterElement typeParameterElement + for (TypeParameterElement2 typeParameterElement in classElement.typeParameters) { DartType? typeParameterElementBound = typeParameterElement.bound; if (typeParameterElementBound == null) { @@ -959,8 +1036,8 @@ class _ReflectorDomain { anyInterfaceElement = classElement; } else { if (typeParameterElementBound is InterfaceType) { - Element? boundElement = typeParameterElementBound.element; - if (boundElement is InterfaceElement) { + Element2? boundElement = typeParameterElementBound.element3; + if (boundElement is InterfaceElement2) { classesToAdd.add(boundElement); } } @@ -970,10 +1047,10 @@ class _ReflectorDomain { } if (mustHaveObject && !hasObject) { // If `mustHaveObject` is true then `anyInterfaceElement` is non-null. - InterfaceElement someInterfaceElement = anyInterfaceElement!; + InterfaceElement2 someInterfaceElement = anyInterfaceElement!; while (!_typeForReflectable(someInterfaceElement).isDartCoreObject) { InterfaceType? someInterfaceType = someInterfaceElement.supertype; - someInterfaceElement = someInterfaceType!.element; + someInterfaceElement = someInterfaceType!.element3; } objectInterfaceElement = someInterfaceElement; await addClass(objectInterfaceElement); @@ -988,21 +1065,21 @@ class _ReflectorDomain { // Record the names of covered members, if requested. if (_capabilities._impliesMemberSymbols) { - for (ExecutableElement executableElement in members.items) { - _world.memberNames.add(executableElement.name); + for (ExecutableElement2 executableElement in members.items) { + _world.memberNames.add(executableElement.name3!); } } // Record the method parameter list shapes, if requested. if (_capabilities._impliesParameterListShapes) { - for (ExecutableElement element in members.items) { + for (ExecutableElement2 element in members.items) { var count = 0; var optionalCount = 0; var names = {}; - for (ParameterElement parameter in element.parameters) { + for (FormalParameterElement parameter in element.formalParameters) { if (!parameter.isNamed) count++; if (parameter.isOptionalPositional) optionalCount++; - if (parameter.isNamed) names.add(parameter.name); + if (parameter.isNamed) names.add(parameter.name3!); } var shape = ParameterListShape(count, optionalCount, names); parameterListShapes.add(shape); @@ -1022,7 +1099,8 @@ class _ReflectorDomain { var typeMirrorsList = []; if (_capabilities._impliesTypes || _capabilities._impliesInstanceInvoke) { for (_ClassDomain classDomain in (await classes).domains) { - typeMirrorsList.add(await _classMirrorCode( + typeMirrorsList.add( + await _classMirrorCode( classDomain, typeParameters, fields, @@ -1037,11 +1115,18 @@ class _ReflectorDomain { libraries, libraryMap, importCollector, - typedefs)); + typedefs, + ), + ); } - for (TypeParameterElement typeParameterElement in typeParameters.items) { - typeMirrorsList.add(await _typeParameterMirrorCode( - typeParameterElement, importCollector, objectInterfaceElement)); + for (TypeParameterElement2 typeParameterElement in typeParameters.items) { + typeMirrorsList.add( + await _typeParameterMirrorCode( + typeParameterElement, + importCollector, + objectInterfaceElement, + ), + ); } } String classMirrorsCode = _formatAsList('m.TypeMirror', typeMirrorsList); @@ -1054,30 +1139,37 @@ class _ReflectorDomain { // Generate code for creation of member mirrors. var topLevelVariablesList = []; - for (TopLevelVariableElement element in topLevelVariables.items) { - topLevelVariablesList.add(await _topLevelVariableMirrorCode( + for (TopLevelVariableElement2 element in topLevelVariables.items) { + topLevelVariablesList.add( + await _topLevelVariableMirrorCode( element, reflectedTypes, reflectedTypesOffset, importCollector, typedefs, - reflectedTypeRequested)); + reflectedTypeRequested, + ), + ); } var fieldsList = []; - for (FieldElement element in fields.items) { - fieldsList.add(await _fieldMirrorCode( + for (FieldElement2 element in fields.items) { + fieldsList.add( + await _fieldMirrorCode( element, reflectedTypes, reflectedTypesOffset, importCollector, typedefs, - reflectedTypeRequested)); + reflectedTypeRequested, + ), + ); } var membersCode = 'null'; if (_capabilities._impliesDeclarations) { var methodsList = []; - for (ExecutableElement executableElement in members.items) { - methodsList.add(await _methodMirrorCode( + for (ExecutableElement2 executableElement in members.items) { + methodsList.add( + await _methodMirrorCode( executableElement, topLevelVariables, fields, @@ -1087,7 +1179,9 @@ class _ReflectorDomain { parameters, importCollector, typedefs, - reflectedTypeRequested)); + reflectedTypeRequested, + ), + ); } Iterable membersList = [ ...topLevelVariablesList, @@ -1101,8 +1195,9 @@ class _ReflectorDomain { var parameterMirrorsCode = 'null'; if (_capabilities._impliesDeclarations) { var parametersList = []; - for (ParameterElement element in parameters.items) { - parametersList.add(await _parameterMirrorCode( + for (FormalParameterElement element in parameters.items) { + parametersList.add( + await _parameterMirrorCode( element, fields, members, @@ -1110,24 +1205,32 @@ class _ReflectorDomain { reflectedTypesOffset, importCollector, typedefs, - reflectedTypeRequested)); + reflectedTypeRequested, + ), + ); } parameterMirrorsCode = _formatAsList('m.ParameterMirror', parametersList); } // Generate code for listing [Type] instances. var typesCodeList = []; - for (InterfaceElement classElement in await classes) { + for (InterfaceElement2 classElement in await classes) { typesCodeList.add(_dynamicTypeCodeOfClass(classElement, importCollector)); } for (ErasableDartType erasableDartType in reflectedTypes.items) { if (erasableDartType.erased) { var interfaceType = erasableDartType.dartType as InterfaceType; typesCodeList.add( - _dynamicTypeCodeOfClass(interfaceType.element, importCollector)); + _dynamicTypeCodeOfClass(interfaceType.element3, importCollector), + ); } else { - typesCodeList.add(await _typeCodeOfClass( - erasableDartType.dartType, importCollector, typedefs)); + typesCodeList.add( + await _typeCodeOfClass( + erasableDartType.dartType, + importCollector, + typedefs, + ), + ); } } String typesCode = _formatAsList('Type', typesCodeList); @@ -1139,7 +1242,8 @@ class _ReflectorDomain { } else { var librariesCodeList = []; for (_LibraryDomain library in libraries.items) { - librariesCodeList.add(await _libraryMirrorCode( + librariesCodeList.add( + await _libraryMirrorCode( library, libraries.indexOf(library)!, members, @@ -1147,14 +1251,16 @@ class _ReflectorDomain { parameterListShapeOf, topLevelVariables, methodsOffset, - importCollector)); + importCollector, + ), + ); } librariesCode = _formatAsList('m.LibraryMirror', librariesCodeList); } - String parameterListShapesCode = _formatAsDynamicList(parameterListShapes - .items - .map((ParameterListShape shape) => shape.code)); + String parameterListShapesCode = _formatAsDynamicList( + parameterListShapes.items.map((ParameterListShape shape) => shape.code), + ); return 'r.ReflectorData($classMirrorsCode, $membersCode, ' '$parameterMirrorsCode, $typesCode, $reflectedTypesOffset, ' @@ -1162,8 +1268,13 @@ class _ReflectorDomain { '$parameterListShapesCode)'; } - Future _computeTypeIndexBase(Element? typeElement, bool isVoid, - bool isDynamic, bool isNever, bool isClassType) async { + Future _computeTypeIndexBase( + Element2? typeElement, + bool isVoid, + bool isDynamic, + bool isNever, + bool isClassType, + ) async { if (_capabilities._impliesTypes) { if (isDynamic || isVoid || isNever) { // The mirror will report 'dynamic', 'void', 'Never', @@ -1184,16 +1295,19 @@ class _ReflectorDomain { } Future _computeVariableTypeIndex( - PropertyInducingElement element, int descriptor) async { + PropertyInducingElement2 element, + int descriptor, + ) async { if (!_capabilities._impliesTypes) return constants.noCapabilityIndex; DartType interfaceType = element.type; if (interfaceType is! InterfaceType) return constants.noCapabilityIndex; return await _computeTypeIndexBase( - interfaceType.element, - descriptor & constants.voidAttribute != 0, - descriptor & constants.dynamicAttribute != 0, - descriptor & constants.neverAttribute != 0, - descriptor & constants.classTypeAttribute != 0); + interfaceType.element3, + descriptor & constants.voidAttribute != 0, + descriptor & constants.dynamicAttribute != 0, + descriptor & constants.neverAttribute != 0, + descriptor & constants.classTypeAttribute != 0, + ); } Future _hasSupportedReflectedTypeArguments(DartType dartType) async { @@ -1209,21 +1323,24 @@ class _ReflectorDomain { } else if (dartType is TypeParameterType || dartType is DynamicType) { return false; } else { - await _severe('`reflectedTypeArguments` where an actual type argument ' - '(possibly nested) is $dartType'); + await _severe( + '`reflectedTypeArguments` where an actual type argument ' + '(possibly nested) is $dartType', + ); return false; } } Future _computeReflectedTypeArguments( - DartType dartType, - Enumerator reflectedTypes, - int reflectedTypesOffset, - _ImportCollector importCollector, - Map typedefs) async { + DartType dartType, + Enumerator reflectedTypes, + int reflectedTypesOffset, + _ImportCollector importCollector, + Map typedefs, + ) async { if (dartType is InterfaceType) { - List typeParameters = - dartType.element.typeParameters; + List typeParameters = + dartType.element3.typeParameters; if (typeParameters.isEmpty) { // We have no formal type parameters, so there cannot be any actual // type arguments. @@ -1249,18 +1366,22 @@ class _ReflectorDomain { if (actualTypeArgument is InterfaceType || actualTypeArgument is VoidType || actualTypeArgument is DynamicType) { - typesIndices.add(_dynamicTypeCodeIndex( + typesIndices.add( + _dynamicTypeCodeIndex( actualTypeArgument, await classes, reflectedTypes, reflectedTypesOffset, - typedefs)); + typedefs, + ), + ); } else { // TODO(eernst) clarify: Are `dynamic` et al `InterfaceType`s? // Otherwise this means "a case that we have not it considered". await _severe( - '`reflectedTypeArguments` where one actual type argument' - ' is $actualTypeArgument'); + '`reflectedTypeArguments` where one actual type argument' + ' is $actualTypeArgument', + ); typesIndices.add(0); } } @@ -1276,52 +1397,56 @@ class _ReflectorDomain { } Future _computeReturnTypeIndex( - ExecutableElement element, int descriptor) async { + ExecutableElement2 element, + int descriptor, + ) async { if (!_capabilities._impliesTypes) return constants.noCapabilityIndex; DartType interfaceType = element.returnType; if (interfaceType is! InterfaceType) return constants.noCapabilityIndex; int result = await _computeTypeIndexBase( - interfaceType.element, - descriptor & constants.voidReturnTypeAttribute != 0, - descriptor & constants.dynamicReturnTypeAttribute != 0, - descriptor & constants.neverReturnTypeAttribute != 0, - descriptor & constants.classReturnTypeAttribute != 0); + interfaceType.element3, + descriptor & constants.voidReturnTypeAttribute != 0, + descriptor & constants.dynamicReturnTypeAttribute != 0, + descriptor & constants.neverReturnTypeAttribute != 0, + descriptor & constants.classReturnTypeAttribute != 0, + ); return result; } Future _computeOwnerIndex( - ExecutableElement element, int descriptor) async { - if (element.enclosingElement is InterfaceElement) { - return (await classes).indexOf(element.enclosingElement); - } else if (element.enclosingElement is CompilationUnitElement) { - return _libraries.indexOf(element.library); + ExecutableElement2 element, + int descriptor, + ) async { + if (element.enclosingElement2 is InterfaceElement2) { + return (await classes).indexOf(element.enclosingElement2!); + } else if (element.enclosingElement2 is LibraryFragment) { + return _libraries.indexOf(element.library2); } await _severe('Unexpected kind of request for owner'); return 0; } - Iterable _gettersOfLibrary(_LibraryDomain library) sync* { - yield* library._accessors - .where((PropertyAccessorElement accessor) => accessor.isGetter); + Iterable _gettersOfLibrary(_LibraryDomain library) sync* { + yield* library._getters; yield* library._declaredFunctions; } - Iterable _settersOfLibrary(_LibraryDomain library) { - return library._accessors - .where((PropertyAccessorElement accessor) => accessor.isSetter); + Iterable _settersOfLibrary(_LibraryDomain library) { + return library._setters; } Future _typeParameterMirrorCode( - TypeParameterElement typeParameterElement, - _ImportCollector importCollector, - InterfaceElement? objectInterfaceElement) async { + TypeParameterElement2 typeParameterElement, + _ImportCollector importCollector, + InterfaceElement2? objectInterfaceElement, + ) async { int? upperBoundIndex = constants.noCapabilityIndex; if (_capabilities._impliesTypeAnnotations) { DartType? bound = typeParameterElement.bound; if (bound == null) { assert(objectInterfaceElement != null); // Missing bound should be reported as the semantic default: `Object`. - // We use an ugly hack to obtain the [InterfaceElement] for `Object`. + // We use an ugly hack to obtain the [InterfaceElement2] for `Object`. upperBoundIndex = (await classes).indexOf(objectInterfaceElement!); assert(upperBoundIndex != null); } else if (bound is DynamicType) { @@ -1336,38 +1461,41 @@ class _ReflectorDomain { } } } - int? ownerIndex = - (await classes).indexOf(typeParameterElement.enclosingElement!); + int? ownerIndex = (await classes).indexOf( + typeParameterElement.enclosingElement2!, + ); // TODO(eernst) implement: Update when type variables support metadata. var metadataCode = _capabilities._supportsMetadata ? '[]' : 'null'; - return "r.TypeVariableMirrorImpl(r'${typeParameterElement.name}', " + return "r.TypeVariableMirrorImpl(r'${typeParameterElement.name3}', " "r'${_qualifiedTypeParameterName(typeParameterElement)}', " '${await _constConstructionCode(importCollector)}, ' '$upperBoundIndex, $ownerIndex, $metadataCode)'; } Future _classMirrorCode( - _ClassDomain classDomain, - Enumerator typeParameters, - Enumerator fields, - int fieldsOffset, - int methodsOffset, - int typeParametersOffset, - Enumerator members, - Enumerator parameterListShapes, - Map parameterListShapeOf, - Enumerator reflectedTypes, - int reflectedTypesOffset, - Enumerator<_LibraryDomain> libraries, - Map libraryMap, - _ImportCollector importCollector, - Map typedefs) async { + _ClassDomain classDomain, + Enumerator typeParameters, + Enumerator fields, + int fieldsOffset, + int methodsOffset, + int typeParametersOffset, + Enumerator members, + Enumerator parameterListShapes, + Map parameterListShapeOf, + Enumerator reflectedTypes, + int reflectedTypesOffset, + Enumerator<_LibraryDomain> libraries, + Map libraryMap, + _ImportCollector importCollector, + Map typedefs, + ) async { int descriptor = _classDescriptor(classDomain._interfaceElement); // Fields go first in [memberMirrors], so they will get the // same index as in [fields]. - Iterable fieldsIndices = - classDomain._declaredFields.map((FieldElement element) { + Iterable fieldsIndices = classDomain._declaredFields.map(( + FieldElement2 element, + ) { return fields.indexOf(element)! + fieldsOffset; }); @@ -1376,56 +1504,62 @@ class _ReflectorDomain { // `fields.length` on the index. Iterable methodsIndices = classDomain._declarations .where(_executableIsntImplicitGetterOrSetter) - .map((ExecutableElement element) { - // TODO(eernst) implement: The "magic" default constructor in `Object` - // (the one that ultimately allocates the memory for _every_ new - // object) has no index, which creates the need to catch a `null` - // here. Search for "magic" to find other occurrences of the same - // issue. For now, we use the index [constants.noCapabilityIndex] - // for this declaration, because it is not yet supported. - // Need to find the correct solution, though! - int? index = members.indexOf(element); - return index == null - ? constants.noCapabilityIndex - : index + methodsOffset; - }); - - String declarationsCode = _capabilities._impliesDeclarations - ? _formatAsConstList('int', [...fieldsIndices, ...methodsIndices]) - : 'const [${constants.noCapabilityIndex}]'; + .map((ExecutableElement2 element) { + // TODO(eernst) implement: The "magic" default constructor in `Object` + // (the one that ultimately allocates the memory for _every_ new + // object) has no index, which creates the need to catch a `null` + // here. Search for "magic" to find other occurrences of the same + // issue. For now, we use the index [constants.noCapabilityIndex] + // for this declaration, because it is not yet supported. + // Need to find the correct solution, though! + int? index = members.indexOf(element); + return index == null + ? constants.noCapabilityIndex + : index + methodsOffset; + }); + + String declarationsCode = + _capabilities._impliesDeclarations + ? _formatAsConstList('int', [...fieldsIndices, ...methodsIndices]) + : 'const [${constants.noCapabilityIndex}]'; // All instance members belong to the behavioral interface, so they // also get an offset of `fields.length`. var instanceMembersCode = 'null'; if (_capabilities._impliesDeclarations) { - instanceMembersCode = _formatAsConstList('int', - classDomain._instanceMembers.map((ExecutableElement element) { - // TODO(eernst) implement: The "magic" default constructor has - // index: noCapabilityIndex; adjust this when support for it has - // been implemented. - int? index = members.indexOf(element); - return index == null - ? constants.noCapabilityIndex - : index + methodsOffset; - })); + instanceMembersCode = _formatAsConstList( + 'int', + classDomain._instanceMembers.map((ExecutableElement2 element) { + // TODO(eernst) implement: The "magic" default constructor has + // index: noCapabilityIndex; adjust this when support for it has + // been implemented. + int? index = members.indexOf(element); + return index == null + ? constants.noCapabilityIndex + : index + methodsOffset; + }), + ); } // All static members belong to the behavioral interface, so they // also get an offset of `fields.length`. var staticMembersCode = 'null'; if (_capabilities._impliesDeclarations) { - staticMembersCode = _formatAsConstList('int', - classDomain._staticMembers.map((ExecutableElement element) { - int? index = members.indexOf(element); - return index == null - ? constants.noCapabilityIndex - : index + methodsOffset; - })); + staticMembersCode = _formatAsConstList( + 'int', + classDomain._staticMembers.map((ExecutableElement2 element) { + int? index = members.indexOf(element); + return index == null + ? constants.noCapabilityIndex + : index + methodsOffset; + }), + ); } - InterfaceElement interfaceElement = classDomain._interfaceElement; - InterfaceElement? superclass = - (await classes).superclassOf(interfaceElement); + InterfaceElement2 interfaceElement = classDomain._interfaceElement; + InterfaceElement2? superclass = (await classes).superclassOf( + interfaceElement, + ); var superclassIndex = '${constants.noCapabilityIndex}'; if (_capabilities._impliesTypeRelations) { @@ -1434,10 +1568,11 @@ class _ReflectorDomain { // convention we make it supported and report it in the same way as // 'dart:mirrors'. Other superclasses use `noCapabilityIndex` to // indicate missing support. - superclassIndex = (interfaceElement is! MixinApplication && - _typeForReflectable(interfaceElement).isDartCoreObject) - ? 'null' - : ((await classes).contains(superclass)) + superclassIndex = + (interfaceElement is! MixinApplication && + _typeForReflectable(interfaceElement).isDartCoreObject) + ? 'null' + : ((await classes).contains(superclass)) ? '${(await classes).indexOf(superclass!)}' : '${constants.noCapabilityIndex}'; } @@ -1451,14 +1586,14 @@ class _ReflectorDomain { constructorsCode = 'const {}'; } else { var mapEntries = []; - for (ConstructorElement constructor in classDomain._constructors) { - InterfaceElement enclosingElement = constructor.enclosingElement; + for (ConstructorElement2 constructor in classDomain._constructors) { + InterfaceElement2 enclosingElement = constructor.enclosingElement2; if (constructor.isFactory || - ((enclosingElement is ClassElement && + ((enclosingElement is ClassElement2 && !enclosingElement.isAbstract) && - enclosingElement is! EnumElement)) { + enclosingElement is! EnumElement2)) { String code = await _constructorCode(constructor, importCollector); - mapEntries.add("r'${constructor.name}': $code"); + mapEntries.add("r'${constructor.name3}': $code"); } } constructorsCode = _formatAsMap(mapEntries); @@ -1468,24 +1603,39 @@ class _ReflectorDomain { var staticSettersCode = 'const {}'; if (interfaceElement is! MixinApplication) { var staticGettersCodeList = []; - for (MethodElement method in classDomain._declaredMethods) { + for (MethodElement2 method in classDomain._declaredMethods) { if (method.isStatic) { - staticGettersCodeList.add(await _staticGettingClosure( - importCollector, interfaceElement, method.name)); + staticGettersCodeList.add( + await _staticGettingClosure( + importCollector, + interfaceElement, + method.name3!, + ), + ); } } - for (PropertyAccessorElement accessor in classDomain._accessors) { - if (accessor.isStatic && accessor.isGetter) { - staticGettersCodeList.add(await _staticGettingClosure( - importCollector, interfaceElement, accessor.name)); + for (GetterElement getter in classDomain._getters) { + if (getter.isStatic) { + staticGettersCodeList.add( + await _staticGettingClosure( + importCollector, + interfaceElement, + getter.name3!, + ), + ); } } staticGettersCode = _formatAsMap(staticGettersCodeList); var staticSettersCodeList = []; - for (PropertyAccessorElement accessor in classDomain._accessors) { - if (accessor.isStatic && accessor.isSetter) { - staticSettersCodeList.add(await _staticSettingClosure( - importCollector, interfaceElement, accessor.name)); + for (SetterElement setter in classDomain._setters) { + if (setter.isStatic) { + staticSettersCodeList.add( + await _staticSettingClosure( + importCollector, + interfaceElement, + setter.name3!, + ), + ); } } staticSettersCode = _formatAsMap(staticSettersCodeList); @@ -1510,24 +1660,30 @@ class _ReflectorDomain { mixinIndex ??= constants.noCapabilityIndex; } - int ownerIndex = _capabilities._supportsLibraries - ? libraries.indexOf(libraryMap[interfaceElement.library]!)! - : constants.noCapabilityIndex; + int ownerIndex = + _capabilities._supportsLibraries + ? libraries.indexOf(libraryMap[interfaceElement.library2]!)! + : constants.noCapabilityIndex; var superinterfaceIndices = 'const [${constants.noCapabilityIndex}]'; if (_capabilities._impliesTypeRelations) { superinterfaceIndices = _formatAsConstList( - 'int', - interfaceElement.interfaces - .map((InterfaceType type) => type.element) - .where((await classes).contains) - .map((await classes).indexOf)); + 'int', + interfaceElement.interfaces + .map((InterfaceType type) => type.element) + .where((await classes).contains) + .map((await classes).indexOf), + ); } String classMetadataCode; if (_capabilities._supportsMetadata) { classMetadataCode = await _extractMetadataCode( - interfaceElement, _resolver, importCollector, _generatedLibraryId); + interfaceElement, + _resolver, + importCollector, + _generatedLibraryId, + ); } else { classMetadataCode = 'null'; } @@ -1536,18 +1692,19 @@ class _ReflectorDomain { var parameterListShapesCode = 'null'; if (_capabilities._impliesParameterListShapes) { - Iterable membersList = [ + Iterable membersList = [ ...classDomain._instanceMembers, ...classDomain._staticMembers, ]; - parameterListShapesCode = - _formatAsMap(membersList.map((ExecutableElement element) { - // shape != null: every method must have its shape in `..shapeOf`. - ParameterListShape shape = parameterListShapeOf[element]!; - // index != null: every shape must be in `..Shapes`. - int index = parameterListShapes.indexOf(shape)!; - return "r'${element.name}': $index"; - })); + parameterListShapesCode = _formatAsMap( + membersList.map((ExecutableElement2 element) { + // shape != null: every method must have its shape in `..shapeOf`. + ParameterListShape shape = parameterListShapeOf[element]!; + // index != null: every shape must be in `..Shapes`. + int index = parameterListShapes.indexOf(shape)!; + return "r'${element.name3}': $index"; + }), + ); } if (interfaceElement.typeParameters.isEmpty) { @@ -1571,12 +1728,15 @@ class _ReflectorDomain { // `implements` this [interfaceElement]. var isCheckList = []; if (interfaceElement.isPrivate || - interfaceElement is MixinElement || - (interfaceElement is ClassElement && interfaceElement.isAbstract) || + interfaceElement is MixinElement2 || + (interfaceElement is ClassElement2 && interfaceElement.isAbstract) || (interfaceElement is MixinApplication && !interfaceElement.isMixinApplication) || !await _isImportable( - interfaceElement, _generatedLibraryId, _resolver)) { + interfaceElement, + _generatedLibraryId, + _resolver, + )) { // Note that this location is dead code until we get support for // anonymous mixin applications using type arguments as generic // classes (currently, no classes will pass the tests above). See @@ -1585,24 +1745,26 @@ class _ReflectorDomain { // no object can be an instance of an anonymous mixin application. isCheckList.add('(o) => false'); } else { - String prefix = importCollector._getPrefix(interfaceElement.library); - isCheckList.add('(o) { return o is $prefix${interfaceElement.name}'); + String prefix = importCollector._getPrefix(interfaceElement.library2); + isCheckList.add('(o) { return o is $prefix${interfaceElement.name3}'); // Add 'is checks' to [list], based on [interfaceElement]. Future helper( - List list, InterfaceElement interfaceElement) async { - Iterable subtypes = - _world.subtypes[interfaceElement] ?? []; + List list, + InterfaceElement2 interfaceElement, + ) async { + Iterable subtypes = + _world.subtypes[interfaceElement] ?? []; for (var subtype in subtypes) { if (subtype.isPrivate || - subtype is MixinElement || - (subtype is ClassElement && subtype.isAbstract) || + subtype is MixinElement2 || + (subtype is ClassElement2 && subtype.isAbstract) || (subtype is MixinApplication && !subtype.isMixinApplication) || !await _isImportable(subtype, _generatedLibraryId, _resolver)) { await helper(list, subtype); } else { - String prefix = importCollector._getPrefix(subtype.library); - list.add(' && o is! $prefix${subtype.name}'); + String prefix = importCollector._getPrefix(subtype.library2); + list.add(' && o is! $prefix${subtype.name3!}'); } } } @@ -1614,21 +1776,23 @@ class _ReflectorDomain { var typeParameterIndices = 'null'; if (_capabilities._impliesDeclarations) { - int indexOf(TypeParameterElement typeParameter) => + int indexOf(TypeParameterElement2 typeParameter) => typeParameters.indexOf(typeParameter)! + typeParametersOffset; typeParameterIndices = _formatAsConstList( - 'int', - interfaceElement.typeParameters - .where(typeParameters.items.contains) - .map(indexOf)); + 'int', + interfaceElement.typeParameters + .where(typeParameters.items.contains) + .map(indexOf), + ); } int? dynamicReflectedTypeIndex = _dynamicTypeCodeIndex( - _typeForReflectable(interfaceElement), - await classes, - reflectedTypes, - reflectedTypesOffset, - typedefs); + _typeForReflectable(interfaceElement), + await classes, + reflectedTypes, + reflectedTypesOffset, + typedefs, + ); return "r.GenericClassMirrorImpl(r'${classDomain._simpleName}', " "r'${_qualifiedName(interfaceElement)}', $descriptor, $classIndex, " @@ -1643,32 +1807,34 @@ class _ReflectorDomain { } Future _methodMirrorCode( - ExecutableElement element, - Enumerator topLevelVariables, - Enumerator fields, - Enumerator members, - Enumerator reflectedTypes, - int reflectedTypesOffset, - Enumerator parameters, - _ImportCollector importCollector, - Map typedefs, - bool reflectedTypeRequested) async { - if (element is PropertyAccessorElement && element.isSynthetic) { + ExecutableElement2 element, + Enumerator topLevelVariables, + Enumerator fields, + Enumerator members, + Enumerator reflectedTypes, + int reflectedTypesOffset, + Enumerator parameters, + _ImportCollector importCollector, + Map typedefs, + bool reflectedTypeRequested, + ) async { + if (element is PropertyAccessorElement2 && element.isSynthetic) { // There is no type propagation, so we declare an `accessorElement`. - PropertyAccessorElement accessorElement = element; - PropertyInducingElement? variable = accessorElement.variable2; - int variableMirrorIndex = variable is TopLevelVariableElement - ? topLevelVariables.indexOf(variable)! - : variable is FieldElement + PropertyAccessorElement2 accessorElement = element; + PropertyInducingElement2? variable = accessorElement.variable3; + int variableMirrorIndex = + variable is TopLevelVariableElement2 + ? topLevelVariables.indexOf(variable)! + : variable is FieldElement2 ? fields.indexOf(variable)! : constants.noCapabilityIndex; int selfIndex = members.indexOf(accessorElement)! + fields.length; - if (accessorElement.isGetter) { + if (accessorElement is GetterElement) { return 'r.ImplicitGetterMirrorImpl(' '${await _constConstructionCode(importCollector)}, ' '$variableMirrorIndex, $selfIndex)'; } else { - assert(accessorElement.isSetter); + assert(accessorElement is SetterElement); return 'r.ImplicitSetterMirrorImpl(' '${await _constConstructionCode(importCollector)}, ' '$variableMirrorIndex, $selfIndex)'; @@ -1678,41 +1844,56 @@ class _ReflectorDomain { // getter or setter. int descriptor = _declarationDescriptor(element); int returnTypeIndex = await _computeReturnTypeIndex(element, descriptor); - int ownerIndex = (await _computeOwnerIndex(element, descriptor)) ?? + int ownerIndex = + (await _computeOwnerIndex(element, descriptor)) ?? constants.noCapabilityIndex; var reflectedTypeArgumentsOfReturnType = 'null'; if (reflectedTypeRequested && _capabilities._impliesTypeRelations) { reflectedTypeArgumentsOfReturnType = await _computeReflectedTypeArguments( - element.returnType, - reflectedTypes, - reflectedTypesOffset, - importCollector, - typedefs); + element.returnType, + reflectedTypes, + reflectedTypesOffset, + importCollector, + typedefs, + ); } - String parameterIndicesCode = _formatAsConstList('int', - element.parameters.map((ParameterElement parameterElement) { - return parameters.indexOf(parameterElement); - })); + String parameterIndicesCode = _formatAsConstList( + 'int', + element.formalParameters.map((FormalParameterElement parameterElement) { + return parameters.indexOf(parameterElement); + }), + ); int reflectedReturnTypeIndex = constants.noCapabilityIndex; if (reflectedTypeRequested) { - reflectedReturnTypeIndex = _typeCodeIndex(element.returnType, - await classes, reflectedTypes, reflectedTypesOffset, typedefs); + reflectedReturnTypeIndex = _typeCodeIndex( + element.returnType, + await classes, + reflectedTypes, + reflectedTypesOffset, + typedefs, + ); } int dynamicReflectedReturnTypeIndex = constants.noCapabilityIndex; if (reflectedTypeRequested) { dynamicReflectedReturnTypeIndex = _dynamicTypeCodeIndex( - element.returnType, - await classes, - reflectedTypes, - reflectedTypesOffset, - typedefs); + element.returnType, + await classes, + reflectedTypes, + reflectedTypesOffset, + typedefs, + ); } - String? metadataCode = _capabilities._supportsMetadata - ? await _extractMetadataCode( - element, _resolver, importCollector, _generatedLibraryId) - : null; - return "r.MethodMirrorImpl(r'${element.name}', $descriptor, " + String? metadataCode = + _capabilities._supportsMetadata + ? await _extractMetadataCode( + element, + _resolver, + importCollector, + _generatedLibraryId, + ) + : null; + return "r.MethodMirrorImpl(r'${element.name3}', $descriptor, " '$ownerIndex, $returnTypeIndex, $reflectedReturnTypeIndex, ' '$dynamicReflectedReturnTypeIndex, ' '$reflectedTypeArgumentsOfReturnType, $parameterIndicesCode, ' @@ -1721,43 +1902,61 @@ class _ReflectorDomain { } Future _topLevelVariableMirrorCode( - TopLevelVariableElement element, - Enumerator reflectedTypes, - int reflectedTypesOffset, - _ImportCollector importCollector, - Map typedefs, - bool reflectedTypeRequested) async { + TopLevelVariableElement2 element, + Enumerator reflectedTypes, + int reflectedTypesOffset, + _ImportCollector importCollector, + Map typedefs, + bool reflectedTypeRequested, + ) async { int descriptor = _topLevelVariableDescriptor(element); - LibraryElement owner = element.library; + LibraryElement2 owner = element.library2; int ownerIndex = _libraries.indexOf(owner) ?? constants.noCapabilityIndex; int classMirrorIndex = await _computeVariableTypeIndex(element, descriptor); - int? reflectedTypeIndex = reflectedTypeRequested - ? _typeCodeIndex(element.type, await classes, reflectedTypes, - reflectedTypesOffset, typedefs) - : constants.noCapabilityIndex; - int? dynamicReflectedTypeIndex = reflectedTypeRequested - ? _dynamicTypeCodeIndex(element.type, await classes, reflectedTypes, - reflectedTypesOffset, typedefs) - : constants.noCapabilityIndex; + int? reflectedTypeIndex = + reflectedTypeRequested + ? _typeCodeIndex( + element.type, + await classes, + reflectedTypes, + reflectedTypesOffset, + typedefs, + ) + : constants.noCapabilityIndex; + int? dynamicReflectedTypeIndex = + reflectedTypeRequested + ? _dynamicTypeCodeIndex( + element.type, + await classes, + reflectedTypes, + reflectedTypesOffset, + typedefs, + ) + : constants.noCapabilityIndex; var reflectedTypeArguments = 'null'; if (reflectedTypeRequested && _capabilities._impliesTypeRelations) { reflectedTypeArguments = await _computeReflectedTypeArguments( - element.type, - reflectedTypes, - reflectedTypesOffset, - importCollector, - typedefs); + element.type, + reflectedTypes, + reflectedTypesOffset, + importCollector, + typedefs, + ); } String? metadataCode; if (_capabilities._supportsMetadata) { metadataCode = await _extractMetadataCode( - element, _resolver, importCollector, _generatedLibraryId); + element, + _resolver, + importCollector, + _generatedLibraryId, + ); } else { // We encode 'without capability' as `null` for metadata, because // it is a `List`, which has no other natural encoding. metadataCode = null; } - return "r.VariableMirrorImpl(r'${element.name}', $descriptor, " + return "r.VariableMirrorImpl(r'${element.name3}', $descriptor, " '$ownerIndex, ${await _constConstructionCode(importCollector)}, ' '$classMirrorIndex, $reflectedTypeIndex, ' '$dynamicReflectedTypeIndex, $reflectedTypeArguments, ' @@ -1765,43 +1964,62 @@ class _ReflectorDomain { } Future _fieldMirrorCode( - FieldElement element, - Enumerator reflectedTypes, - int reflectedTypesOffset, - _ImportCollector importCollector, - Map typedefs, - bool reflectedTypeRequested) async { + FieldElement2 element, + Enumerator reflectedTypes, + int reflectedTypesOffset, + _ImportCollector importCollector, + Map typedefs, + bool reflectedTypeRequested, + ) async { int descriptor = _fieldDescriptor(element); - int ownerIndex = (await classes).indexOf(element.enclosingElement) ?? + int ownerIndex = + (await classes).indexOf(element.enclosingElement2) ?? constants.noCapabilityIndex; int classMirrorIndex = await _computeVariableTypeIndex(element, descriptor); - int reflectedTypeIndex = reflectedTypeRequested - ? _typeCodeIndex(element.type, await classes, reflectedTypes, - reflectedTypesOffset, typedefs) - : constants.noCapabilityIndex; - int dynamicReflectedTypeIndex = reflectedTypeRequested - ? _dynamicTypeCodeIndex(element.type, await classes, reflectedTypes, - reflectedTypesOffset, typedefs) - : constants.noCapabilityIndex; + int reflectedTypeIndex = + reflectedTypeRequested + ? _typeCodeIndex( + element.type, + await classes, + reflectedTypes, + reflectedTypesOffset, + typedefs, + ) + : constants.noCapabilityIndex; + int dynamicReflectedTypeIndex = + reflectedTypeRequested + ? _dynamicTypeCodeIndex( + element.type, + await classes, + reflectedTypes, + reflectedTypesOffset, + typedefs, + ) + : constants.noCapabilityIndex; var reflectedTypeArguments = 'null'; if (reflectedTypeRequested && _capabilities._impliesTypeRelations) { reflectedTypeArguments = await _computeReflectedTypeArguments( - element.type, - reflectedTypes, - reflectedTypesOffset, - importCollector, - typedefs); + element.type, + reflectedTypes, + reflectedTypesOffset, + importCollector, + typedefs, + ); } String? metadataCode; if (_capabilities._supportsMetadata) { metadataCode = await _extractMetadataCode( - element, _resolver, importCollector, _generatedLibraryId); + element, + _resolver, + importCollector, + _generatedLibraryId, + ); } else { // We encode 'without capability' as `null` for metadata, because // it is a `List`, which has no other natural encoding. metadataCode = null; } - return "r.VariableMirrorImpl(r'${element.name}', $descriptor, " + return "r.VariableMirrorImpl(r'${element.name3}', $descriptor, " '$ownerIndex, ${await _constConstructionCode(importCollector)}, ' '$classMirrorIndex, $reflectedTypeIndex, ' '$dynamicReflectedTypeIndex, $reflectedTypeArguments, $metadataCode)'; @@ -1817,18 +2035,19 @@ class _ReflectorDomain { /// added to `ReflectorData.types` after the elements of [classes] have been /// added. int _typeCodeIndex( - DartType dartType, - _InterfaceElementEnhancedSet classes, - Enumerator reflectedTypes, - int reflectedTypesOffset, - Map typedefs) { + DartType dartType, + _InterfaceElementEnhancedSet classes, + Enumerator reflectedTypes, + int reflectedTypesOffset, + Map typedefs, + ) { // The types `dynamic` and `void` are handled via `...Attribute` bits. if (dartType is DynamicType) return constants.noCapabilityIndex; if (dartType is VoidType) return constants.noCapabilityIndex; if (dartType is InterfaceType) { if (dartType.typeArguments.isEmpty) { // A plain, non-generic class, may be handled already. - InterfaceElement interfaceElement = dartType.element; + InterfaceElement2 interfaceElement = dartType.element3; if (classes.contains(interfaceElement)) { return classes.indexOf(interfaceElement)!; } @@ -1869,17 +2088,18 @@ class _ReflectorDomain { /// [reflectedTypes], because the elements in there will be added to /// `ReflectorData.types` after the elements of [classes] have been added. int _dynamicTypeCodeIndex( - DartType dartType, - _InterfaceElementEnhancedSet classes, - Enumerator reflectedTypes, - int reflectedTypesOffset, - Map typedefs) { + DartType dartType, + _InterfaceElementEnhancedSet classes, + Enumerator reflectedTypes, + int reflectedTypesOffset, + Map typedefs, + ) { // The types `void` and `dynamic` are handled via the `...Attribute` bits. if (dartType is VoidType || dartType is DynamicType) { return constants.noCapabilityIndex; } if (dartType is InterfaceType) { - InterfaceElement interfaceElement = dartType.element; + InterfaceElement2 interfaceElement = dartType.element3; if (classes.contains(interfaceElement)) { return classes.indexOf(interfaceElement)!; } @@ -1887,8 +2107,10 @@ class _ReflectorDomain { // and iff it has type arguments we must specify that it should be erased // (if there are no type arguments we will use "not erased": erasure // makes no difference and we don't want to have two identical copies). - var erasableDartType = - ErasableDartType(dartType, erased: dartType.typeArguments.isNotEmpty); + var erasableDartType = ErasableDartType( + dartType, + erased: dartType.typeArguments.isNotEmpty, + ); reflectedTypes.add(erasableDartType); return reflectedTypes.indexOf(erasableDartType)! + reflectedTypesOffset; } else if (dartType is VoidType) { @@ -1914,8 +2136,10 @@ class _ReflectorDomain { /// Returns true iff the given [type] is not and does not contain a free /// type variable. [typeVariablesInScope] gives the names of type variables /// which are in scope (and hence not free in the relevant context). - bool _hasNoFreeTypeVariables(DartType type, - [Set? typeVariablesInScope]) { + bool _hasNoFreeTypeVariables( + DartType type, [ + Set? typeVariablesInScope, + ]) { if (type is TypeParameterType && (typeVariablesInScope == null || !typeVariablesInScope.contains(type.getDisplayString()))) { @@ -1923,8 +2147,9 @@ class _ReflectorDomain { } if (type is InterfaceType) { if (type.typeArguments.isEmpty) return true; - return type.typeArguments - .every((type) => _hasNoFreeTypeVariables(type, typeVariablesInScope)); + return type.typeArguments.every( + (type) => _hasNoFreeTypeVariables(type, typeVariablesInScope), + ); } // Possible kinds of types at this point (apart from several types // indicating an error that we do not expect here): `BottomTypeImpl`, @@ -1947,45 +2172,56 @@ class _ReflectorDomain { /// name or a fully spelled-out generic function type (and it has no /// effect when [dartType] is not a generic function type). Future _typeCodeOfTypeArgument( - DartType dartType, - _ImportCollector importCollector, - Set typeVariablesInScope, - Map typedefs, - {bool useNameOfGenericFunctionType = true}) async { + DartType dartType, + _ImportCollector importCollector, + Set typeVariablesInScope, + Map typedefs, { + bool useNameOfGenericFunctionType = true, + }) async { Future fail() async { - InterfaceElement? element = - dartType is InterfaceType ? dartType.element : null; - log.warning(await _formatDiagnosticMessage( + InterfaceElement2? element = + dartType is InterfaceType ? dartType.element3 : null; + log.warning( + await _formatDiagnosticMessage( 'Attempt to generate code for an ' 'unsupported kind of type: $dartType (${dartType.runtimeType}). ' 'Generating `dynamic`.', element, - _resolver)); + _resolver, + ), + ); return 'dynamic'; } if (dartType is DynamicType) return 'dynamic'; if (dartType is InterfaceType) { - InterfaceElement interfaceElement = dartType.element; + InterfaceElement2 interfaceElement = dartType.element3; if ((interfaceElement is MixinApplication && - interfaceElement.declaredName == null) || + interfaceElement.firstFragment.name2 == null) || interfaceElement.isPrivate) { return await fail(); } - String prefix = importCollector._getPrefix(interfaceElement.library); + String prefix = importCollector._getPrefix(interfaceElement.library2); if (interfaceElement.typeParameters.isEmpty) { - return '$prefix${interfaceElement.name}'; + return '$prefix${interfaceElement.name3}'; } else { if (dartType.typeArguments.every( - (type) => _hasNoFreeTypeVariables(type, typeVariablesInScope))) { + (type) => _hasNoFreeTypeVariables(type, typeVariablesInScope), + )) { var argumentList = []; for (DartType typeArgument in dartType.typeArguments) { - argumentList.add(await _typeCodeOfTypeArgument( - typeArgument, importCollector, typeVariablesInScope, typedefs, - useNameOfGenericFunctionType: useNameOfGenericFunctionType)); + argumentList.add( + await _typeCodeOfTypeArgument( + typeArgument, + importCollector, + typeVariablesInScope, + typedefs, + useNameOfGenericFunctionType: useNameOfGenericFunctionType, + ), + ); } String arguments = argumentList.join(', '); - return '$prefix${interfaceElement.name}<$arguments>'; + return '$prefix${interfaceElement.name3}<$arguments>'; } else { return await fail(); } @@ -1993,53 +2229,73 @@ class _ReflectorDomain { } else if (dartType is VoidType) { return 'void'; } else if (dartType is FunctionType) { - final Element? dartTypeElement = dartType.alias?.element; - if (dartTypeElement is TypeAliasElement) { - String prefix = importCollector._getPrefix(dartTypeElement.library); - return '$prefix${dartTypeElement.name}'; + final Element2? dartTypeElement = dartType.alias?.element2; + if (dartTypeElement is TypeAliasElement2) { + String prefix = importCollector._getPrefix(dartTypeElement.library2); + return '$prefix${dartTypeElement.name3}'; } else { // Generic function types need separate `typedef`s. if (dartType.typeFormals.isNotEmpty) { if (useNameOfGenericFunctionType) { // Requested: just the name of the typedef; get it and return. - int dartTypeNumber = typedefs.containsKey(dartType) - ? typedefs[dartType]! - : typedefNumber++; + int dartTypeNumber = + typedefs.containsKey(dartType) + ? typedefs[dartType]! + : typedefNumber++; return _typedefName(dartTypeNumber); } else { // Requested: the spelled-out generic function type; continue. - typeVariablesInScope - .addAll(dartType.typeFormals.map((element) => element.name)); + typeVariablesInScope.addAll( + dartType.typeFormals.map((element) => element.name), + ); } } - String returnType = await _typeCodeOfTypeArgument(dartType.returnType, - importCollector, typeVariablesInScope, typedefs, - useNameOfGenericFunctionType: useNameOfGenericFunctionType); + String returnType = await _typeCodeOfTypeArgument( + dartType.returnType, + importCollector, + typeVariablesInScope, + typedefs, + useNameOfGenericFunctionType: useNameOfGenericFunctionType, + ); var typeArguments = ''; - if (dartType.typeFormals.isNotEmpty) { - Iterable typeArgumentList = dartType.typeFormals.map( - (TypeParameterElement typeParameter) => typeParameter.toString()); + if (dartType.typeParameters.isNotEmpty) { + Iterable typeArgumentList = dartType.typeParameters.map( + (TypeParameterElement2 typeParameter) => typeParameter.toString(), + ); typeArguments = '<${typeArgumentList.join(', ')}>'; } var argumentTypes = ''; if (dartType.normalParameterTypes.isNotEmpty) { var normalParameterTypeList = []; for (DartType parameterType in dartType.normalParameterTypes) { - normalParameterTypeList.add(await _typeCodeOfTypeArgument( - parameterType, importCollector, typeVariablesInScope, typedefs, - useNameOfGenericFunctionType: useNameOfGenericFunctionType)); + normalParameterTypeList.add( + await _typeCodeOfTypeArgument( + parameterType, + importCollector, + typeVariablesInScope, + typedefs, + useNameOfGenericFunctionType: useNameOfGenericFunctionType, + ), + ); } argumentTypes = normalParameterTypeList.join(', '); } if (dartType.optionalParameterTypes.isNotEmpty) { var optionalParameterTypeList = []; for (DartType parameterType in dartType.optionalParameterTypes) { - optionalParameterTypeList.add(await _typeCodeOfTypeArgument( - parameterType, importCollector, typeVariablesInScope, typedefs, - useNameOfGenericFunctionType: useNameOfGenericFunctionType)); + optionalParameterTypeList.add( + await _typeCodeOfTypeArgument( + parameterType, + importCollector, + typeVariablesInScope, + typedefs, + useNameOfGenericFunctionType: useNameOfGenericFunctionType, + ), + ); } var connector = argumentTypes.isEmpty ? '' : ', '; - argumentTypes = '$argumentTypes$connector' + argumentTypes = + '$argumentTypes$connector' '[${optionalParameterTypeList.join(', ')}]'; } if (dartType.namedParameterTypes.isNotEmpty) { @@ -2048,12 +2304,17 @@ class _ReflectorDomain { for (String name in parameterMap.keys) { DartType parameterType = parameterMap[name]!; String typeCode = await _typeCodeOfTypeArgument( - parameterType, importCollector, typeVariablesInScope, typedefs, - useNameOfGenericFunctionType: useNameOfGenericFunctionType); + parameterType, + importCollector, + typeVariablesInScope, + typedefs, + useNameOfGenericFunctionType: useNameOfGenericFunctionType, + ); namedParameterTypeList.add('$typeCode $name'); } var connector = argumentTypes.isEmpty ? '' : ', '; - argumentTypes = '$argumentTypes$connector' + argumentTypes = + '$argumentTypes$connector' '{${namedParameterTypeList.join(', ')}}'; } return '$returnType Function$typeArguments($argumentTypes)'; @@ -2071,14 +2332,17 @@ class _ReflectorDomain { /// evaluating the [typeDefiningElement] as an expression in the library /// where it occurs. [importCollector] is used to find the library prefixes /// needed in order to obtain values from other libraries. - Future _typeCodeOfClass(DartType dartType, - _ImportCollector importCollector, Map typedefs) async { + Future _typeCodeOfClass( + DartType dartType, + _ImportCollector importCollector, + Map typedefs, + ) async { var typeVariablesInScope = {}; // None at this level. if (dartType is DynamicType) return 'dynamic'; if (dartType is InterfaceType) { - InterfaceElement interfaceElement = dartType.element; + InterfaceElement2 interfaceElement = dartType.element3; if ((interfaceElement is MixinApplication && - interfaceElement.declaredName == null) || + interfaceElement.firstFragment.name2 == null) || interfaceElement.isPrivate) { // The test for an anonymous mixin application above may be dead code: // Currently no test uses an anonymous mixin application to reach this @@ -2092,14 +2356,18 @@ class _ReflectorDomain { // class. return "const r.FakeType(r'${_qualifiedName(interfaceElement)}')"; } - String prefix = importCollector._getPrefix(interfaceElement.library); + String prefix = importCollector._getPrefix(interfaceElement.library2); if (interfaceElement.typeParameters.isEmpty) { - return '$prefix${interfaceElement.name}'; + return '$prefix${interfaceElement.name3}'; } else { if (dartType.typeArguments.every(_hasNoFreeTypeVariables)) { String typeArgumentCode = await _typeCodeOfTypeArgument( - dartType, importCollector, typeVariablesInScope, typedefs, - useNameOfGenericFunctionType: true); + dartType, + importCollector, + typeVariablesInScope, + typedefs, + useNameOfGenericFunctionType: true, + ); return 'const m.TypeValue<$typeArgumentCode>().type'; } else { String arguments = dartType.typeArguments @@ -2115,32 +2383,43 @@ class _ReflectorDomain { // A function type is inherently not private, so we ignore privacy. // Note that some function types are _claimed_ to be private in analyzer // 0.36.4, so it is a bug to test for it. - final Element? dartTypeElement = dartType.alias?.element; - if (dartTypeElement is TypeAliasElement) { - String prefix = importCollector._getPrefix(dartTypeElement.library); - return '$prefix${dartTypeElement.name}'; + final Element2? dartTypeElement = dartType.alias?.element2; + if (dartTypeElement is TypeAliasElement2) { + String prefix = importCollector._getPrefix(dartTypeElement.library2); + return '$prefix${dartTypeElement.name3}'; } else { if (dartType.typeFormals.isNotEmpty) { // `dartType` is a generic function type, so we must use a // separately generated `typedef` to obtain a `Type` for it. return await _typeCodeOfTypeArgument( - dartType, importCollector, typeVariablesInScope, typedefs, - useNameOfGenericFunctionType: true); + dartType, + importCollector, + typeVariablesInScope, + typedefs, + useNameOfGenericFunctionType: true, + ); } else { String typeArgumentCode = await _typeCodeOfTypeArgument( - dartType, importCollector, typeVariablesInScope, typedefs); + dartType, + importCollector, + typeVariablesInScope, + typedefs, + ); return 'const m.TypeValue<$typeArgumentCode>().type'; } } } else { - InterfaceElement? element = - dartType is InterfaceType ? dartType.element : null; - log.warning(await _formatDiagnosticMessage( + InterfaceElement2? element = + dartType is InterfaceType ? dartType.element3 : null; + log.warning( + await _formatDiagnosticMessage( 'Attempt to generate code for an ' 'unsupported kind of type: $dartType (${dartType.runtimeType}). ' 'Generating `dynamic`.', element, - _resolver)); + _resolver, + ), + ); return 'dynamic'; } } @@ -2152,21 +2431,24 @@ class _ReflectorDomain { /// that we get the fully dynamic instantiation if it is a generic class. /// [importCollector] is used to find the library prefixes needed in order /// to obtain values from other libraries. - String _dynamicTypeCodeOfClass(TypeDefiningElement typeDefiningElement, - _ImportCollector importCollector) { - DartType? type = typeDefiningElement is InterfaceElement - ? _typeForReflectable(typeDefiningElement) - : null; + String _dynamicTypeCodeOfClass( + TypeDefiningElement2 typeDefiningElement, + _ImportCollector importCollector, + ) { + DartType? type = + typeDefiningElement is InterfaceElement2 + ? _typeForReflectable(typeDefiningElement) + : null; if (type is DynamicType) return 'dynamic'; if (type is InterfaceType) { - InterfaceElement interfaceElement = type.element; + InterfaceElement2 interfaceElement = type.element3; if ((interfaceElement is MixinApplication && - interfaceElement.declaredName == null) || + interfaceElement.firstFragment.name2 == null) || interfaceElement.isPrivate) { return "const r.FakeType(r'${_qualifiedName(interfaceElement)}')"; } - String prefix = importCollector._getPrefix(interfaceElement.library); - return '$prefix${interfaceElement.name}'; + String prefix = importCollector._getPrefix(interfaceElement.library2); + return '$prefix${interfaceElement.name3}'; } else if (type is VoidType) { return 'const m.TypeValue().type'; } else { @@ -2180,34 +2462,38 @@ class _ReflectorDomain { } Future _libraryMirrorCode( - _LibraryDomain libraryDomain, - int libraryIndex, - Enumerator members, - Enumerator parameterListShapes, - Map parameterListShapeOf, - Enumerator variables, - int methodsOffset, - _ImportCollector importCollector) async { - LibraryElement library = libraryDomain._libraryElement; + _LibraryDomain libraryDomain, + int libraryIndex, + Enumerator members, + Enumerator parameterListShapes, + Map parameterListShapeOf, + Enumerator variables, + int methodsOffset, + _ImportCollector importCollector, + ) async { + LibraryElement2 library = libraryDomain._libraryElement; var gettersCodeList = []; - for (ExecutableElement getter in _gettersOfLibrary(libraryDomain)) { + for (ExecutableElement2 getter in _gettersOfLibrary(libraryDomain)) { gettersCodeList.add( - await _topLevelGettingClosure(importCollector, library, getter.name)); + await _topLevelGettingClosure(importCollector, library, getter.name3!), + ); } String gettersCode = _formatAsMap(gettersCodeList); var settersCodeList = []; - for (PropertyAccessorElement setter in _settersOfLibrary(libraryDomain)) { + for (PropertyAccessorElement2 setter in _settersOfLibrary(libraryDomain)) { settersCodeList.add( - await _topLevelSettingClosure(importCollector, library, setter.name)); + await _topLevelSettingClosure(importCollector, library, setter.name3!), + ); } String settersCode = _formatAsMap(settersCodeList); // Fields go first in [memberMirrors], so they will get the // same index as in [fields]. - Iterable variableIndices = - libraryDomain._declaredVariables.map((TopLevelVariableElement element) { + Iterable variableIndices = libraryDomain._declaredVariables.map(( + TopLevelVariableElement2 element, + ) { return variables.indexOf(element)!; }); @@ -2216,10 +2502,10 @@ class _ReflectorDomain { // `fields.length` on the index. Iterable methodIndices = libraryDomain._declarations .where(_executableIsntImplicitGetterOrSetter) - .map((ExecutableElement element) { - int index = members.indexOf(element)!; - return index + methodsOffset; - }); + .map((ExecutableElement2 element) { + int index = members.indexOf(element)!; + return index + methodsOffset; + }); var declarationsCode = 'const [${constants.noCapabilityIndex}]'; if (_capabilities._impliesDeclarations) { @@ -2252,7 +2538,11 @@ class _ReflectorDomain { String metadataCode; if (_capabilities._supportsMetadata) { metadataCode = await _extractMetadataCode( - library, _resolver, importCollector, _generatedLibraryId); + library, + _resolver, + importCollector, + _generatedLibraryId, + ); } else { metadataCode = 'null'; } @@ -2260,33 +2550,35 @@ class _ReflectorDomain { var parameterListShapesCode = 'null'; if (_capabilities._impliesParameterListShapes) { parameterListShapesCode = _formatAsMap( - libraryDomain._declarations.map((ExecutableElement element) { - // shape != null: every method has a shape in `..shapeOf`. - ParameterListShape shape = parameterListShapeOf[element]!; - // index != null: every shape is in `..Shapes`. - int index = parameterListShapes.indexOf(shape)!; - return "r'${element.name}': $index"; - })); + libraryDomain._declarations.map((ExecutableElement2 element) { + // shape != null: every method has a shape in `..shapeOf`. + ParameterListShape shape = parameterListShapeOf[element]!; + // index != null: every shape is in `..Shapes`. + int index = parameterListShapes.indexOf(shape)!; + return "r'${element.name3}': $index"; + }), + ); } - return "r.LibraryMirrorImpl(r'${library.name}', $uriCode, " + return "r.LibraryMirrorImpl(r'${library.name3}', $uriCode, " '${await _constConstructionCode(importCollector)}, ' '$declarationsCode, $gettersCode, $settersCode, $metadataCode, ' '$parameterListShapesCode)'; } Future _parameterMirrorCode( - ParameterElement element, - Enumerator fields, - Enumerator members, - Enumerator reflectedTypes, - int reflectedTypesOffset, - _ImportCollector importCollector, - Map typedefs, - bool reflectedTypeRequested) async { + FormalParameterElement element, + Enumerator fields, + Enumerator members, + Enumerator reflectedTypes, + int reflectedTypesOffset, + _ImportCollector importCollector, + Map typedefs, + bool reflectedTypeRequested, + ) async { int descriptor = _parameterDescriptor(element); int ownerIndex = - members.indexOf(element.enclosingElement!)! + fields.length; + members.indexOf(element.enclosingElement2!)! + fields.length; int classMirrorIndex = constants.noCapabilityIndex; if (_capabilities._impliesTypes) { if (descriptor & constants.dynamicAttribute != 0 || @@ -2300,37 +2592,51 @@ class _ReflectorDomain { // capability is absent. DartType elementType = element.type; if (elementType is InterfaceType) { - InterfaceElement elementTypeElement = elementType.element; - classMirrorIndex = (await classes).contains(elementTypeElement) - ? (await classes).indexOf(elementTypeElement)! - : constants.noCapabilityIndex; + InterfaceElement2 elementTypeElement = elementType.element3; + classMirrorIndex = + (await classes).contains(elementTypeElement) + ? (await classes).indexOf(elementTypeElement)! + : constants.noCapabilityIndex; } else { classMirrorIndex = constants.noCapabilityIndex; } } } - int reflectedTypeIndex = reflectedTypeRequested - ? _typeCodeIndex(element.type, await classes, reflectedTypes, - reflectedTypesOffset, typedefs) - : constants.noCapabilityIndex; - int dynamicReflectedTypeIndex = reflectedTypeRequested - ? _dynamicTypeCodeIndex(element.type, await classes, reflectedTypes, - reflectedTypesOffset, typedefs) - : constants.noCapabilityIndex; + int reflectedTypeIndex = + reflectedTypeRequested + ? _typeCodeIndex( + element.type, + await classes, + reflectedTypes, + reflectedTypesOffset, + typedefs, + ) + : constants.noCapabilityIndex; + int dynamicReflectedTypeIndex = + reflectedTypeRequested + ? _dynamicTypeCodeIndex( + element.type, + await classes, + reflectedTypes, + reflectedTypesOffset, + typedefs, + ) + : constants.noCapabilityIndex; var reflectedTypeArguments = 'null'; if (reflectedTypeRequested && _capabilities._impliesTypeRelations) { reflectedTypeArguments = await _computeReflectedTypeArguments( - element.type, - reflectedTypes, - reflectedTypesOffset, - importCollector, - typedefs); + element.type, + reflectedTypes, + reflectedTypesOffset, + importCollector, + typedefs, + ); } var metadataCode = 'null'; if (_capabilities._supportsMetadata) { // TODO(eernst): 'dart:*' is not considered valid. To survive, we // return the empty metadata for elements from 'dart:*'. Issue 173. - if (_isPlatformLibrary(element.library!)) { + if (_isPlatformLibrary(element.library2!)) { metadataCode = 'const []'; } else { var node = @@ -2341,17 +2647,22 @@ class _ReflectorDomain { metadataCode = 'const []'; } else { metadataCode = await _extractMetadataCode( - element, _resolver, importCollector, _generatedLibraryId); + element, + _resolver, + importCollector, + _generatedLibraryId, + ); } } } String code = await _extractDefaultValueCode(importCollector, element); var defaultValueCode = code.isEmpty ? 'null' : code; - var parameterSymbolCode = descriptor & constants.namedAttribute != 0 - ? '#${element.name}' - : 'null'; + var parameterSymbolCode = + descriptor & constants.namedAttribute != 0 + ? '#${element.name3}' + : 'null'; - return "r.ParameterMirrorImpl(r'${element.name}', $descriptor, " + return "r.ParameterMirrorImpl(r'${element.name3}', $descriptor, " '$ownerIndex, ${await _constConstructionCode(importCollector)}, ' '$classMirrorIndex, $reflectedTypeIndex, $dynamicReflectedTypeIndex, ' '$reflectedTypeArguments, $metadataCode, $defaultValueCode, ' @@ -2361,61 +2672,76 @@ class _ReflectorDomain { /// Given an [importCollector] and a [parameterElement], returns '' if there /// is no default value, otherwise returns code for an expression that /// evaluates to said default value. - Future _extractDefaultValueCode(_ImportCollector importCollector, - ParameterElement parameterElement) async { + Future _extractDefaultValueCode( + _ImportCollector importCollector, + FormalParameterElement parameterElement, + ) async { // TODO(eernst): 'dart:*' is not considered valid. To survive, we return // '' for all declarations from there. Issue 173. - if (_isPlatformLibrary(parameterElement.library!)) return ''; - var parameterNode = await _getDeclarationAst(parameterElement, _resolver) - as FormalParameter?; + if (_isPlatformLibrary(parameterElement.library2!)) return ''; + var parameterNode = + await _getDeclarationAst(parameterElement, _resolver) + as FormalParameter?; // The node can be null because the declaration is synthetic, e.g., // the parameter of an induced setter; they have no default value. if (parameterNode is DefaultFormalParameter && parameterNode.defaultValue != null) { - return await _extractConstantCode(parameterNode.defaultValue!, - importCollector, _generatedLibraryId, _resolver); + return await _extractConstantCode( + parameterNode.defaultValue!, + importCollector, + _generatedLibraryId, + _resolver, + ); } else if (parameterElement is DefaultFieldFormalParameterElementImpl) { Expression? defaultValue = parameterElement.constantInitializer; if (defaultValue != null) { return await _extractConstantCode( - defaultValue, importCollector, _generatedLibraryId, _resolver); + defaultValue, + importCollector, + _generatedLibraryId, + _resolver, + ); } } return ''; } } -DartType _typeForReflectable(InterfaceElement interfaceElement) { +DartType _typeForReflectable(InterfaceElement2 interfaceElement) { // TODO(eernst): This getter is used to inspect subclass relationships, // so there is no need to handle type parameters/arguments. So we might // be able to improve performance by working on classes as such. var typeArguments = List.filled( - interfaceElement.typeParameters.length, - interfaceElement.library.typeProvider.dynamicType); + interfaceElement.typeParameters.length, + interfaceElement.library2.typeProvider.dynamicType, + ); return interfaceElement.instantiate( - typeArguments: typeArguments, nullabilitySuffix: NullabilitySuffix.star); + typeArguments: typeArguments, + nullabilitySuffix: NullabilitySuffix.star, + ); } /// Auxiliary class used by `classes`. Its `expand` method expands /// its argument to a fixed point, based on the `successors` method. -class _SubtypesFixedPoint extends FixedPoint { - final Map> subtypes; +class _SubtypesFixedPoint extends FixedPoint { + final Map> subtypes; _SubtypesFixedPoint(this.subtypes); /// Returns all the immediate subtypes of the given [classMirror]. @override - Future> successors( - final InterfaceElement interfaceElement) async { - Iterable? interfaceElements = subtypes[interfaceElement]; - return interfaceElements ?? []; + Future> successors( + final InterfaceElement2 interfaceElement, + ) async { + Iterable? interfaceElements = subtypes[interfaceElement]; + return interfaceElements ?? []; } } /// Auxiliary class used by `classes`. Its `expand` method expands /// its argument to a fixed point, based on the `successors` method. -class _SuperclassFixedPoint extends FixedPoint { - final Map upwardsClosureBounds; +class _SuperclassFixedPoint extends FixedPoint { + final Map upwardsClosureBounds; final bool mixinsRequested; _SuperclassFixedPoint(this.upwardsClosureBounds, this.mixinsRequested); @@ -2432,8 +2758,9 @@ class _SuperclassFixedPoint extends FixedPoint { /// TODO(eernst) implement: When mixins can have nontrivial superclasses /// we may or may not wish to enforce the bounds even for mixins. @override - Future> successors( - InterfaceElement element) async { + Future> successors( + InterfaceElement2 element, + ) async { // A mixin application is handled by its regular subclasses. if (element is MixinApplication) return []; // If upper bounds not satisfied then there are no successors. @@ -2443,9 +2770,9 @@ class _SuperclassFixedPoint extends FixedPoint { if (workingSuperType == null) { return []; // "Superclass of [Object]", ignore. } - InterfaceElement workingSuperclass = workingSuperType.element; + InterfaceElement2 workingSuperclass = workingSuperType.element3; - var result = []; + var result = []; if (_includedByUpwardsClosure(workingSuperclass)) { result.add(workingSuperclass); @@ -2463,17 +2790,23 @@ class _SuperclassFixedPoint extends FixedPoint { // is done with [subClass]. var superclass = workingSuperclass; for (InterfaceType mixin in element.mixins) { - InterfaceElement mixinClass = mixin.element; + InterfaceElement2 mixinClass = mixin.element3; if (mixinsRequested) result.add(mixinClass); - InterfaceElement? subClass = + InterfaceElement2? subClass = mixin == element.mixins.last ? element : null; - String? name = subClass == null - ? null - : (element is MixinApplication && element.isMixinApplication - ? element.name - : null); - InterfaceElement mixinApplication = MixinApplication( - name, superclass, mixinClass, element.library, subClass); + String? name = + subClass == null + ? null + : (element is MixinApplication && element.isMixinApplication + ? element.name3 + : null); + InterfaceElement2 mixinApplication = MixinApplication( + name, + superclass, + mixinClass, + element.library2, + subClass, + ); // We have already ensured that `workingSuperclass` is a // subclass of a bound (if any); the value of `superclass` is // either `workingSuperclass` or one of its superclasses created @@ -2487,9 +2820,9 @@ class _SuperclassFixedPoint extends FixedPoint { return result; } - bool _includedByUpwardsClosure(InterfaceElement interfaceElement) { - bool helper(InterfaceElement interfaceElement, bool direct) { - bool isSuperclassOfInterfaceElement(InterfaceElement bound) { + bool _includedByUpwardsClosure(InterfaceElement2 interfaceElement) { + bool helper(InterfaceElement2 interfaceElement, bool direct) { + bool isSuperclassOfInterfaceElement(InterfaceElement2 bound) { if (interfaceElement == bound) { // If `!direct` then the desired subclass relation exists. // If `direct` then the original `interfaceElement` is equal to @@ -2498,7 +2831,7 @@ class _SuperclassFixedPoint extends FixedPoint { } InterfaceType? interfaceElementSupertype = interfaceElement.supertype; if (interfaceElementSupertype == null) return false; - return helper(interfaceElementSupertype.element, false); + return helper(interfaceElementSupertype.element3, false); } return upwardsClosureBounds.keys.any(isSuperclassOfInterfaceElement); @@ -2510,15 +2843,16 @@ class _SuperclassFixedPoint extends FixedPoint { /// Auxiliary function used by `classes`. Its `expand` method /// expands its argument to a fixed point, based on the `successors` method. -Set _mixinApplicationsOfClasses( - Set classes) { - var mixinApplications = {}; - for (InterfaceElement interfaceElement in classes) { +Set _mixinApplicationsOfClasses( + Set classes, +) { + var mixinApplications = {}; + for (InterfaceElement2 interfaceElement in classes) { // Mixin-applications are handled when they are created. if (interfaceElement is MixinApplication) continue; InterfaceType? supertype = interfaceElement.supertype; if (supertype == null) continue; // "Superclass of [Object]", ignore. - InterfaceElement superclass = supertype.element; + InterfaceElement2 superclass = supertype.element3; // Note that we iterate from the most general mixin to more specific ones, // that is, with `class C extends B with M1, M2..` we visit `M1` before // `M2`; this ensures that the right `superclass` is available for each @@ -2526,17 +2860,23 @@ Set _mixinApplicationsOfClasses( // of each [MixinApplication] when it is a regular class (not a mixin // application), otherwise [null], which is done with [subClass]. for (InterfaceType mixin in interfaceElement.mixins) { - InterfaceElement mixinClass = mixin.element; - InterfaceElement? subClass = + InterfaceElement2 mixinClass = mixin.element3; + InterfaceElement2? subClass = mixin == interfaceElement.mixins.last ? interfaceElement : null; - String? name = subClass == null - ? null - : (interfaceElement is MixinApplication && - interfaceElement.isMixinApplication - ? interfaceElement.name - : null); - InterfaceElement mixinApplication = MixinApplication( - name, superclass, mixinClass, interfaceElement.library, subClass); + String? name = + subClass == null + ? null + : (interfaceElement is MixinApplication && + interfaceElement.isMixinApplication + ? interfaceElement.name3 + : null); + InterfaceElement2 mixinApplication = MixinApplication( + name, + superclass, + mixinClass, + interfaceElement.library2, + subClass, + ); mixinApplications.add(mixinApplication); superclass = mixinApplication; } @@ -2545,7 +2885,7 @@ Set _mixinApplicationsOfClasses( } /// Auxiliary type used by [_AnnotationClassFixedPoint]. -typedef _ElementToDomain = _ClassDomain Function(InterfaceElement); +typedef _ElementToDomain = _ClassDomain Function(InterfaceElement2); /// Auxiliary class used by `classes`. Its `expand` method /// expands its argument to a fixed point, based on the `successors` method. @@ -2553,19 +2893,23 @@ typedef _ElementToDomain = _ClassDomain Function(InterfaceElement); /// classes (that we must avoid attempting to use because they are unavailable /// to user programs). [generatedLibraryId] must refer to the asset where the /// generated code will be stored; it is used in the same check. -class _AnnotationClassFixedPoint extends FixedPoint { +class _AnnotationClassFixedPoint extends FixedPoint { final Resolver resolver; final AssetId generatedLibraryId; final _ElementToDomain elementToDomain; _AnnotationClassFixedPoint( - this.resolver, this.generatedLibraryId, this.elementToDomain); + this.resolver, + this.generatedLibraryId, + this.elementToDomain, + ); /// Returns the classes that occur as return types of covered methods or in /// type annotations of covered variables and parameters of covered methods, @override - Future> successors( - InterfaceElement interfaceElement) async { + Future> successors( + InterfaceElement2 interfaceElement, + ) async { if (!await _isImportable(interfaceElement, generatedLibraryId, resolver)) { return []; } @@ -2574,39 +2918,41 @@ class _AnnotationClassFixedPoint extends FixedPoint { // Mixin-applications do not add further methods and fields. if (classDomain._interfaceElement is MixinApplication) return []; - var result = []; + var result = []; // Traverse type annotations to find successors. Note that we cannot // abstract the many redundant elements below, because `yield` cannot // occur in a local function. - for (FieldElement fieldElement in classDomain._declaredFields) { + for (FieldElement2 fieldElement in classDomain._declaredFields) { DartType fieldType = fieldElement.type; if (fieldType is InterfaceType) { - result.add(fieldType.element); + result.add(fieldType.element3); } } - for (ParameterElement parameterElement in classDomain._declaredParameters) { + for (FormalParameterElement parameterElement + in classDomain._declaredParameters) { DartType parameterType = parameterElement.type; if (parameterType is InterfaceType) { - result.add(parameterType.element); + result.add(parameterType.element3); } } - for (ParameterElement parameterElement in classDomain._instanceParameters) { + for (FormalParameterElement parameterElement + in classDomain._instanceParameters) { DartType parameterType = parameterElement.type; if (parameterType is InterfaceType) { - result.add(parameterType.element); + result.add(parameterType.element3); } } - for (ExecutableElement executableElement in classDomain._declaredMethods) { + for (ExecutableElement2 executableElement in classDomain._declaredMethods) { DartType executableReturnType = executableElement.returnType; if (executableReturnType is InterfaceType) { - result.add(executableReturnType.element); + result.add(executableReturnType.element3); } } - for (ExecutableElement executableElement in classDomain._instanceMembers) { + for (ExecutableElement2 executableElement in classDomain._instanceMembers) { DartType executableReturnType = executableElement.returnType; if (executableReturnType is InterfaceType) { - result.add(executableReturnType.element); + result.add(executableReturnType.element3); } } return result; @@ -2643,10 +2989,13 @@ String _settingClosure(String setterName) { } // Auxiliary function used by `_generateCode`. -Future _staticGettingClosure(_ImportCollector importCollector, - InterfaceElement interfaceElement, String getterName) async { - String className = interfaceElement.name; - String prefix = importCollector._getPrefix(interfaceElement.library); +Future _staticGettingClosure( + _ImportCollector importCollector, + InterfaceElement2 interfaceElement, + String getterName, +) async { + String className = interfaceElement.name3!; + String prefix = importCollector._getPrefix(interfaceElement.library2); // Operators cannot be static. if (_isPrivateName(getterName)) { await _severe('Cannot access private name $getterName', interfaceElement); @@ -2658,13 +3007,16 @@ Future _staticGettingClosure(_ImportCollector importCollector, } // Auxiliary function used by `_generateCode`. -Future _staticSettingClosure(_ImportCollector importCollector, - InterfaceElement interfaceElement, String setterName) async { +Future _staticSettingClosure( + _ImportCollector importCollector, + InterfaceElement2 interfaceElement, + String setterName, +) async { assert(setterName.substring(setterName.length - 1) == '='); // The [setterName] includes the '=', remove it. String name = setterName.substring(0, setterName.length - 1); - String className = interfaceElement.name; - String prefix = importCollector._getPrefix(interfaceElement.library); + String className = interfaceElement.name3!; + String prefix = importCollector._getPrefix(interfaceElement.library2); if (_isPrivateName(setterName)) { await _severe('Cannot access private name $setterName', interfaceElement); } @@ -2675,8 +3027,11 @@ Future _staticSettingClosure(_ImportCollector importCollector, } // Auxiliary function used by `_generateCode`. -Future _topLevelGettingClosure(_ImportCollector importCollector, - LibraryElement library, String getterName) async { +Future _topLevelGettingClosure( + _ImportCollector importCollector, + LibraryElement2 library, + String getterName, +) async { String prefix = importCollector._getPrefix(library); // Operators cannot be top-level. if (_isPrivateName(getterName)) { @@ -2686,8 +3041,11 @@ Future _topLevelGettingClosure(_ImportCollector importCollector, } // Auxiliary function used by `_generateCode`. -Future _topLevelSettingClosure(_ImportCollector importCollector, - LibraryElement library, String setterName) async { +Future _topLevelSettingClosure( + _ImportCollector importCollector, + LibraryElement2 library, + String setterName, +) async { assert(setterName.substring(setterName.length - 1) == '='); // The [setterName] includes the '=', remove it. String name = setterName.substring(0, setterName.length - 1); @@ -2703,50 +3061,60 @@ String _typedefName(int id) => 'typedef$id'; /// Information about reflectability for a given library. class _LibraryDomain { - /// Element describing the target library. - final LibraryElement _libraryElement; + /// Element2 describing the target library. + final LibraryElement2 _libraryElement; /// Fields declared by [_libraryElement] and included for reflection support, /// according to the reflector described by the [_reflectorDomain]; /// obtained by filtering `_libraryElement.fields`. - final Iterable _declaredVariables; + final Iterable _declaredVariables; /// Methods which are declared by [_libraryElement] and included for /// reflection support, according to the reflector described by /// [_reflectorDomain]; obtained by filtering `_libraryElement.functions`. - final Iterable _declaredFunctions; + final Iterable _declaredFunctions; /// Formal parameters declared by one of the [_declaredFunctions]. - final Iterable _declaredParameters; + final Iterable _declaredParameters; - /// Getters and setters possessed by [_libraryElement] and included for + /// Getters possessed by [_libraryElement] and included for /// reflection support, according to the reflector described by - /// [_reflectorDomain]; obtained by filtering `_libraryElement.accessors`. + /// [_reflectorDomain]. /// Note that it includes declared as well as synthetic accessors, implicitly /// created as getters/setters for fields. - final Iterable _accessors; + final Iterable _getters; + + /// Setters possessed by [_libraryElement] and included for + /// reflection support, according to the reflector described by + /// [_reflectorDomain]. + /// Note that it includes declared as well as synthetic accessors, implicitly + /// created as getters/setters for fields. + final Iterable _setters; /// The reflector domain that holds [this] object as one of its /// library domains. final _ReflectorDomain _reflectorDomain; _LibraryDomain( - this._libraryElement, - this._declaredVariables, - this._declaredFunctions, - this._declaredParameters, - this._accessors, - this._reflectorDomain); + this._libraryElement, + this._declaredVariables, + this._declaredFunctions, + this._declaredParameters, + this._getters, + this._setters, + this._reflectorDomain, + ); /// Returns the declared methods, accessors and constructors in /// [_interfaceElement]. Note that this includes synthetic getters and /// setters, and omits fields; in other words, it provides the /// behavioral point of view on the class. Also note that this is not /// the same semantics as that of `declarations` in [ClassMirror]. - Iterable get _declarations => [ - ..._declaredFunctions, - ..._accessors, - ]; + Iterable get _declarations => [ + ..._declaredFunctions, + ..._getters, + ..._setters, + ]; @override String toString() { @@ -2769,55 +3137,64 @@ class _LibraryDomain { /// Information about reflectability for a given class. class _ClassDomain { - /// Element describing the target class. - final InterfaceElement _interfaceElement; + /// Element2 describing the target class. + final InterfaceElement2 _interfaceElement; /// Fields declared by [_interfaceElement] and included for reflection support, /// according to the reflector described by the [_reflectorDomain]; /// obtained by filtering `_interfaceElement.fields`. - final Iterable _declaredFields; + final Iterable _declaredFields; /// Methods which are declared by [_interfaceElement] and included for /// reflection support, according to the reflector described by /// [reflectorDomain]; obtained by filtering `_interfaceElement.methods`. - final Iterable _declaredMethods; + final Iterable _declaredMethods; /// Formal parameters declared by one of the [_declaredMethods]. - final Iterable _declaredParameters; + final Iterable _declaredParameters; - /// Getters and setters possessed by [_interfaceElement] and included for + /// Getters possessed by [_interfaceElement] and included for /// reflection support, according to the reflector described by - /// [reflectorDomain]; obtained by filtering `_interfaceElement.accessors`. + /// [reflectorDomain]. /// Note that it includes declared as well as synthetic accessors, /// implicitly created as getters/setters for fields. - final Iterable _accessors; + final Iterable _getters; + + /// Setters possessed by [_interfaceElement] and included for + /// reflection support, according to the reflector described by + /// [reflectorDomain]. + /// Note that it includes declared as well as synthetic accessors, + /// implicitly created as getters/setters for fields. + final Iterable _setters; /// Constructors declared by [_interfaceElement] and included for reflection /// support, according to the reflector described by [_reflectorDomain]; /// obtained by filtering `_interfaceElement.constructors`. - final Iterable _constructors; + final Iterable _constructors; /// The reflector domain that holds [this] object as one of its /// class domains. final _ReflectorDomain _reflectorDomain; _ClassDomain( - this._interfaceElement, - this._declaredFields, - this._declaredMethods, - this._declaredParameters, - this._accessors, - this._constructors, - this._reflectorDomain); + this._interfaceElement, + this._declaredFields, + this._declaredMethods, + this._declaredParameters, + this._getters, + this._setters, + this._constructors, + this._reflectorDomain, + ); String get _simpleName { // TODO(eernst) clarify: Decide whether this should be simplified // by adding a method implementation to `MixinApplication`. - InterfaceElement interfaceElement = _interfaceElement; + InterfaceElement2 interfaceElement = _interfaceElement; if (interfaceElement is MixinApplication && interfaceElement.isMixinApplication) { // This is the case `class B = A with M;`. - return interfaceElement.name; + return interfaceElement.name3!; } else if (interfaceElement is MixinApplication) { // This is the case `class B extends A with M1, .. Mk {..}` // where `interfaceElement` denotes one of the mixin applications @@ -2825,19 +3202,19 @@ class _ClassDomain { // excluded. List mixins = interfaceElement.mixins; var superclassType = interfaceElement.supertype as InterfaceType; - InterfaceElement superclassTypeElement = superclassType.element; + InterfaceElement2 superclassTypeElement = superclassType.element3; String superclassName = _qualifiedName(superclassTypeElement); var name = StringBuffer(superclassName); var firstSeparator = true; for (var mixin in mixins) { name.write(firstSeparator ? ' with ' : ', '); - name.write(_qualifiedName(mixin.element)); + name.write(_qualifiedName(mixin.element3)); firstSeparator = false; } return name.toString(); } else { // This is a regular class, i.e., we can use its declared name. - return interfaceElement.name; + return interfaceElement.name3!; } } @@ -2846,56 +3223,60 @@ class _ClassDomain { /// setters, and omits fields; in other words, it provides the /// behavioral point of view on the class. Also note that this is not /// the same semantics as that of `declarations` in [ClassMirror]. - Iterable get _declarations => [ - // TODO(sigurdm) feature: Include type variables (if we keep them). - ..._declaredMethods, - ..._accessors, - ..._constructors, - ]; + Iterable get _declarations => [ + // TODO(sigurdm) feature: Include type variables (if we keep them). + ..._declaredMethods, + ..._getters, + ..._setters, + ..._constructors, + ]; /// Finds all instance members by going through the class hierarchy. - Iterable get _instanceMembers { - Map helper(InterfaceElement interfaceElement) { - Map? member = + Iterable get _instanceMembers { + Map helper(InterfaceElement2 interfaceElement) { + Map? member = _reflectorDomain._instanceMemberCache[interfaceElement]; if (member != null) return member; - var result = {}; + var result = {}; - void addIfCapable(String name, ExecutableElement member) { + void addIfCapable(String name, ExecutableElement2 member) { if (member.isPrivate) return; // If [member] is a synthetic accessor created from a field, search for // the metadata on the original field. List metadata = - (member is PropertyAccessorElement && member.isSynthetic) - ? (member.variable2?.metadata ?? const []) - : member.metadata; + (member is PropertyAccessorElement2 && member.isSynthetic) + ? member.variable3?.metadata2.annotations ?? const [] + : member.metadata2.annotations; List? getterMetadata; if (_reflectorDomain._capabilities._impliesCorrespondingSetters && - member is PropertyAccessorElement && - !member.isSynthetic && - member.isSetter) { - PropertyAccessorElement? correspondingGetter = - member.correspondingGetter; - getterMetadata = correspondingGetter?.metadata; + member is SetterElement && + !member.isSynthetic) { + GetterElement? correspondingGetter = member.correspondingGetter; + getterMetadata = correspondingGetter?.metadata2.annotations; } if (_reflectorDomain._capabilities.supportsInstanceInvoke( - member.library.typeSystem, member.name, metadata, getterMetadata)) { + member.library2.typeSystem, + member.name3!, + metadata, + getterMetadata, + )) { result[name] = member; } } void addTypeIfCapable(InterfaceType type) { - helper(type.element).forEach(addIfCapable); + helper(type.element3).forEach(addIfCapable); } - void addIfCapableConcreteInstance(ExecutableElement member) { + void addIfCapableConcreteInstance(ExecutableElement2 member) { if (!member.isAbstract && !member.isStatic) { - addIfCapable(member.name, member); + addIfCapable(member.name3!, member); } } - Map cacheResult( - Map result) { + Map cacheResult( + Map result, + ) { result = Map.unmodifiable(result); _reflectorDomain._instanceMemberCache[interfaceElement] = result; return result; @@ -2908,12 +3289,13 @@ class _ClassDomain { } InterfaceType? superclassType = interfaceElement.supertype; if (superclassType is InterfaceType) { - InterfaceElement superclassElement = superclassType.element; + InterfaceElement2 superclassElement = superclassType.element3; helper(superclassElement).forEach(addIfCapable); } interfaceElement.mixins.forEach(addTypeIfCapable); - interfaceElement.methods.forEach(addIfCapableConcreteInstance); - interfaceElement.accessors.forEach(addIfCapableConcreteInstance); + interfaceElement.methods2.forEach(addIfCapableConcreteInstance); + interfaceElement.getters2.forEach(addIfCapableConcreteInstance); + interfaceElement.setters2.forEach(addIfCapableConcreteInstance); return cacheResult(result); } @@ -2922,56 +3304,63 @@ class _ClassDomain { } /// Finds all parameters of instance members. - Iterable get _instanceParameters { - var result = []; + Iterable get _instanceParameters { + var result = []; if (_reflectorDomain._capabilities._impliesDeclarations) { - for (ExecutableElement executableElement in _instanceMembers) { - result.addAll(executableElement.parameters); + for (ExecutableElement2 executableElement in _instanceMembers) { + result.addAll(executableElement.formalParameters); } } return result; } /// Finds all static members. - Iterable get _staticMembers { - var result = []; + Iterable get _staticMembers { + var result = []; if (_interfaceElement is MixinApplication) return result; - void possiblyAddMethod(MethodElement method) { + void possiblyAddMethod(MethodElement2 method) { if (method.isStatic && !method.isPrivate && _reflectorDomain._capabilities.supportsStaticInvoke( - method.library.typeSystem, method.name, method.metadata, null)) { + method.library2.typeSystem, + method.name3!, + method.metadata2.annotations, + null, + )) { result.add(method); } } - void possiblyAddAccessor(PropertyAccessorElement accessor) { + void possiblyAddAccessor(PropertyAccessorElement2 accessor) { if (!accessor.isStatic || accessor.isPrivate) return; // If [member] is a synthetic accessor created from a field, search for // the metadata on the original field. - List metadata = accessor.isSynthetic - ? (accessor.variable2?.metadata ?? const []) - : accessor.metadata; + List metadata = + accessor.isSynthetic + ? (accessor.variable3?.metadata2.annotations ?? const []) + : accessor.metadata2.annotations; List? getterMetadata; if (_reflectorDomain._capabilities._impliesCorrespondingSetters && - accessor.isSetter && + accessor is SetterElement && !accessor.isSynthetic) { - PropertyAccessorElement? correspondingGetter = + PropertyAccessorElement2? correspondingGetter = accessor.correspondingGetter; - getterMetadata = correspondingGetter?.metadata; + getterMetadata = correspondingGetter?.metadata2.annotations; } if (_reflectorDomain._capabilities.supportsStaticInvoke( - accessor.library.typeSystem, - accessor.name, - metadata, - getterMetadata)) { + accessor.library2.typeSystem, + accessor.name3!, + metadata, + getterMetadata, + )) { result.add(accessor); } } - _interfaceElement.methods.forEach(possiblyAddMethod); - _interfaceElement.accessors.forEach(possiblyAddAccessor); + _interfaceElement.methods2.forEach(possiblyAddMethod); + _interfaceElement.getters2.forEach(possiblyAddAccessor); + _interfaceElement.setters2.forEach(possiblyAddAccessor); return result; } @@ -2993,9 +3382,10 @@ class _Capabilities { } bool _supportsMeta( - TypeSystem typeSystem, - ec.MetadataQuantifiedCapability capability, - Iterable? metadata) { + TypeSystem typeSystem, + ec.MetadataQuantifiedCapability capability, + Iterable? metadata, + ) { if (metadata == null) return false; var result = false; DartType capabilityType = _typeForReflectable(capability.metadataType); @@ -3009,11 +3399,12 @@ class _Capabilities { } bool _supportsInstanceInvoke( - TypeSystem typeSystem, - List capabilities, - String methodName, - Iterable metadata, - Iterable? getterMetadata) { + TypeSystem typeSystem, + List capabilities, + String methodName, + Iterable metadata, + Iterable? getterMetadata, + ) { for (ec.ReflectCapability capability in capabilities) { // Handle API based capabilities. if (capability is ec.InstanceInvokeCapability && @@ -3031,8 +3422,13 @@ class _Capabilities { // Check if we can retry, using the corresponding getter. if (_isSetterName(methodName) && getterMetadata != null) { - return _supportsInstanceInvoke(typeSystem, capabilities, - _setterNameToGetterName(methodName), getterMetadata, null); + return _supportsInstanceInvoke( + typeSystem, + capabilities, + _setterNameToGetterName(methodName), + getterMetadata, + null, + ); } // All options exhausted, give up. @@ -3040,10 +3436,11 @@ class _Capabilities { } bool _supportsNewInstance( - TypeSystem typeSystem, - Iterable capabilities, - String constructorName, - Iterable metadata) { + TypeSystem typeSystem, + Iterable capabilities, + String constructorName, + Iterable metadata, + ) { for (ec.ReflectCapability capability in capabilities) { // Handle API based capabilities. if (capability is ec.NamePatternCapability) { @@ -3072,34 +3469,42 @@ class _Capabilities { // TODO(sigurdm) future: Find a way to cache these. Perhaps take an // element instead of name+metadata. bool supportsInstanceInvoke( - TypeSystem typeSystem, - String methodName, - Iterable metadata, - Iterable? getterMetadata) { + TypeSystem typeSystem, + String methodName, + Iterable metadata, + Iterable? getterMetadata, + ) { return _supportsInstanceInvoke( - typeSystem, - _capabilities, - methodName, - _getEvaluatedMetadata(metadata), - getterMetadata == null ? null : _getEvaluatedMetadata(getterMetadata)); + typeSystem, + _capabilities, + methodName, + _getEvaluatedMetadata(metadata), + getterMetadata == null ? null : _getEvaluatedMetadata(getterMetadata), + ); } bool supportsNewInstance( - TypeSystem typeSystem, - String constructorName, - Iterable metadata, - LibraryElement libraryElement, - Resolver resolver) { - return _supportsNewInstance(typeSystem, _capabilities, constructorName, - _getEvaluatedMetadata(metadata)); + TypeSystem typeSystem, + String constructorName, + Iterable metadata, + LibraryElement2 libraryElement, + Resolver resolver, + ) { + return _supportsNewInstance( + typeSystem, + _capabilities, + constructorName, + _getEvaluatedMetadata(metadata), + ); } bool _supportsTopLevelInvoke( - TypeSystem typeSystem, - List capabilities, - String methodName, - Iterable metadata, - Iterable? getterMetadata) { + TypeSystem typeSystem, + List capabilities, + String methodName, + Iterable metadata, + Iterable? getterMetadata, + ) { for (ec.ReflectCapability capability in capabilities) { // Handle API based capabilities. if ((capability is ec.TopLevelInvokeCapability) && @@ -3116,8 +3521,13 @@ class _Capabilities { // Check if we can retry, using the corresponding getter. if (_isSetterName(methodName) && getterMetadata != null) { - return _supportsTopLevelInvoke(typeSystem, capabilities, - _setterNameToGetterName(methodName), getterMetadata, null); + return _supportsTopLevelInvoke( + typeSystem, + capabilities, + _setterNameToGetterName(methodName), + getterMetadata, + null, + ); } // All options exhausted, give up. @@ -3125,11 +3535,12 @@ class _Capabilities { } bool _supportsStaticInvoke( - TypeSystem typeSystem, - List capabilities, - String methodName, - Iterable metadata, - Iterable? getterMetadata) { + TypeSystem typeSystem, + List capabilities, + String methodName, + Iterable metadata, + Iterable? getterMetadata, + ) { for (ec.ReflectCapability capability in capabilities) { // Handle API based capabilities. if (capability is ec.StaticInvokeCapability && @@ -3147,8 +3558,13 @@ class _Capabilities { // Check if we can retry, using the corresponding getter. if (_isSetterName(methodName) && getterMetadata != null) { - return _supportsStaticInvoke(typeSystem, capabilities, - _setterNameToGetterName(methodName), getterMetadata, null); + return _supportsStaticInvoke( + typeSystem, + capabilities, + _setterNameToGetterName(methodName), + getterMetadata, + null, + ); } // All options exhausted, give up. @@ -3156,36 +3572,42 @@ class _Capabilities { } bool supportsTopLevelInvoke( - TypeSystem typeSystem, - String methodName, - Iterable metadata, - Iterable? getterMetadata) { + TypeSystem typeSystem, + String methodName, + Iterable metadata, + Iterable? getterMetadata, + ) { return _supportsTopLevelInvoke( - typeSystem, - _capabilities, - methodName, - _getEvaluatedMetadata(metadata), - getterMetadata == null ? null : _getEvaluatedMetadata(getterMetadata)); + typeSystem, + _capabilities, + methodName, + _getEvaluatedMetadata(metadata), + getterMetadata == null ? null : _getEvaluatedMetadata(getterMetadata), + ); } bool supportsStaticInvoke( - TypeSystem typeSystem, - String methodName, - Iterable metadata, - Iterable? getterMetadata) { + TypeSystem typeSystem, + String methodName, + Iterable metadata, + Iterable? getterMetadata, + ) { return _supportsStaticInvoke( - typeSystem, - _capabilities, - methodName, - _getEvaluatedMetadata(metadata), - getterMetadata == null ? null : _getEvaluatedMetadata(getterMetadata)); + typeSystem, + _capabilities, + methodName, + _getEvaluatedMetadata(metadata), + getterMetadata == null ? null : _getEvaluatedMetadata(getterMetadata), + ); } late final bool _supportsMetadata = _capabilities.any( - (ec.ReflectCapability capability) => capability is ec.MetadataCapability); + (ec.ReflectCapability capability) => capability is ec.MetadataCapability, + ); - late final bool _supportsUri = _capabilities - .any((ec.ReflectCapability capability) => capability is ec.UriCapability); + late final bool _supportsUri = _capabilities.any( + (ec.ReflectCapability capability) => capability is ec.UriCapability, + ); /// Returns [true] iff these [Capabilities] specify reflection support /// where the set of classes must be downwards closed, i.e., extra classes @@ -3193,16 +3615,18 @@ class _Capabilities { /// metadata and global quantifiers, such that coverage on a class `C` /// implies coverage of every class `D` such that `D` is a subtype of `C`. late final bool _impliesDownwardsClosure = _capabilities.any( - (ec.ReflectCapability capability) => - capability == ec.subtypeQuantifyCapability); + (ec.ReflectCapability capability) => + capability == ec.subtypeQuantifyCapability, + ); /// Returns [true] iff these [Capabilities] specify reflection support where /// the set of included classes must be upwards closed, i.e., extra classes /// must be added beyond the ones that are directly included as reflectable /// because we must support operations like `superclass`. late final bool _impliesUpwardsClosure = _capabilities.any( - (ec.ReflectCapability capability) => - capability is ec.SuperclassQuantifyCapability); + (ec.ReflectCapability capability) => + capability is ec.SuperclassQuantifyCapability, + ); /// Returns [true] iff these [Capabilities] specify that classes which have /// been used for mixin application for an included class must themselves @@ -3215,8 +3639,9 @@ class _Capabilities { /// be included (if you have `class B extends A with M ..` then the class `M` /// will be included if `_impliesMixins`). late final bool _impliesTypeRelations = _capabilities.any( - (ec.ReflectCapability capability) => - capability is ec.TypeRelationsCapability); + (ec.ReflectCapability capability) => + capability is ec.TypeRelationsCapability, + ); /// Returns [true] iff these [Capabilities] specify that type annotations /// modeled by mirrors should also get support for their base level [Type] @@ -3224,8 +3649,9 @@ class _Capabilities { /// The relevant kinds of mirrors are variable mirrors, parameter mirrors, /// and (for the return type) method mirrors. late final bool _impliesReflectedType = _capabilities.any( - (ec.ReflectCapability capability) => - capability == ec.reflectedTypeCapability); + (ec.ReflectCapability capability) => + capability == ec.reflectedTypeCapability, + ); /// Maps each upper bound specified for the upwards closure to whether the /// bound itself is excluded, as indicated by `excludeUpperBound` in the @@ -3233,30 +3659,34 @@ class _Capabilities { /// provides a listing of the upper bounds, and the map itself may then /// be consulted for each key (`if (myClosureBounds[key]) ..`) in order to /// take `excludeUpperBound` into account. - Future> get _upwardsClosureBounds async { - var result = {}; + Future> get _upwardsClosureBounds async { + var result = {}; for (ec.ReflectCapability capability in _capabilities) { if (capability is ec.SuperclassQuantifyCapability) { - Element? element = capability.upperBound; + Element2? element = capability.upperBound; if (element == null) continue; // Means [Object], trivially satisfied. - if (element is InterfaceElement) { + if (element is InterfaceElement2) { result[element] = capability.excludeUpperBound; } else { - await _severe('Unexpected kind of upper bound specified ' - 'for a `SuperclassQuantifyCapability`: $element.'); + await _severe( + 'Unexpected kind of upper bound specified ' + 'for a `SuperclassQuantifyCapability`: $element.', + ); } } } return result; } - late final bool _impliesDeclarations = - _capabilities.any((ec.ReflectCapability capability) { + late final bool _impliesDeclarations = _capabilities.any(( + ec.ReflectCapability capability, + ) { return capability is ec.DeclarationsCapability; }); - late final bool _impliesMemberSymbols = - _capabilities.any((ec.ReflectCapability capability) { + late final bool _impliesMemberSymbols = _capabilities.any(( + ec.ReflectCapability capability, + ) { return capability == ec.delegateCapability; }); @@ -3270,8 +3700,9 @@ class _Capabilities { return !_impliesDeclarations; } - late final bool _impliesTypes = - _capabilities.any((ec.ReflectCapability capability) { + late final bool _impliesTypes = _capabilities.any(( + ec.ReflectCapability capability, + ) { return capability is ec.TypeCapability; }); @@ -3283,38 +3714,43 @@ class _Capabilities { /// they are simply absent if there are no class mirrors (so we cannot call /// them and then get a "cannot do this without a class mirror" error in the /// implementation). - late final bool _impliesInstanceInvoke = - _capabilities.any((ec.ReflectCapability capability) { + late final bool _impliesInstanceInvoke = _capabilities.any(( + ec.ReflectCapability capability, + ) { return capability is ec.InstanceInvokeCapability || capability is ec.InstanceInvokeMetaCapability; }); late final bool _impliesTypeAnnotations = _capabilities.any( - (ec.ReflectCapability capability) => - capability is ec.TypeAnnotationQuantifyCapability); + (ec.ReflectCapability capability) => + capability is ec.TypeAnnotationQuantifyCapability, + ); late final bool _impliesTypeAnnotationClosure = _capabilities.any( - (ec.ReflectCapability capability) => - capability is ec.TypeAnnotationQuantifyCapability && - capability.transitive == true); + (ec.ReflectCapability capability) => + capability is ec.TypeAnnotationQuantifyCapability && + capability.transitive == true, + ); late final bool _impliesCorrespondingSetters = _capabilities.any( - (ec.ReflectCapability capability) => - capability == ec.correspondingSetterQuantifyCapability); + (ec.ReflectCapability capability) => + capability == ec.correspondingSetterQuantifyCapability, + ); late final bool _supportsLibraries = _capabilities.any( - (ec.ReflectCapability capability) => capability is ec.LibraryCapability); + (ec.ReflectCapability capability) => capability is ec.LibraryCapability, + ); } /// Collects the libraries that needs to be imported, and gives each library /// a unique prefix. class _ImportCollector { - final _mapping = {}; + final _mapping = {}; int _count = 0; /// Returns the prefix associated with [library]. Iff it is non-empty /// it includes the period. - String _getPrefix(LibraryElement library) { + String _getPrefix(LibraryElement2 library) { if (library.isDartCore) return ''; String? prefix = _mapping[library]; if (prefix != null) return prefix; @@ -3326,7 +3762,7 @@ class _ImportCollector { /// Adds [library] to the collected libraries and generate a prefix for it if /// it has not been encountered before. - void _addLibrary(LibraryElement library) { + void _addLibrary(LibraryElement2 library) { if (library.isDartCore) return; String? prefix = _mapping[library]; if (prefix != null) return; @@ -3335,7 +3771,7 @@ class _ImportCollector { _mapping[library] = prefix; } - Iterable get _libraries => _mapping.keys; + Iterable get _libraries => _mapping.keys; } // TODO(eernst) future: Keep in mind, with reference to @@ -3361,8 +3797,8 @@ int _processedEntryPointCount = 0; class BuilderImplementation { late final Resolver _resolver; - var _libraries = []; - final _librariesByName = {}; + var _libraries = []; + final _librariesByName = {}; late final bool _formatted; late final List _suppressedWarnings; @@ -3393,22 +3829,24 @@ class BuilderImplementation { /// programs must use exactly one specific URI to import /// reflectable.dart. So we use [Reflectable.thisClassId] which is very /// unlikely to occur with the same value elsewhere by accident. - bool _equalsClassReflectable(InterfaceElement type) { - FieldElement? idField = type.getField('thisClassId'); + bool _equalsClassReflectable(InterfaceElement2 type) { + FieldElement2? idField = type.getField('thisClassId'); if (idField == null || !idField.isStatic) return false; DartObject? constantValue = idField.computeConstantValue(); return constantValue?.toStringValue() == reflectable_class_constants.id; } - /// Returns the InterfaceElement in the target program which corresponds to class + /// Returns the InterfaceElement2 in the target program which corresponds to class /// [Reflectable]. - Future _findReflectableInterfaceElement( - LibraryElement reflectableLibrary) async { - for (CompilationUnitElement unit in reflectableLibrary.units) { - for (InterfaceElement type in unit.classes) { - if (type.name == reflectable_class_constants.name && - _equalsClassReflectable(type)) { - return type; + Future _findReflectableInterfaceElement( + LibraryElement2 reflectableLibrary, + ) async { + for (LibraryFragment fragment in reflectableLibrary.fragments) { + for (ClassFragment fragment in fragment.classes2) { + final element = fragment.element; + if (element.name3 == reflectable_class_constants.name && + _equalsClassReflectable(element)) { + return element; } } // No need to check `unit.enums`: [Reflectable] is not an enum. @@ -3419,7 +3857,9 @@ class BuilderImplementation { /// Returns true iff [possibleSubtype] is a direct subclass of [type]. bool _isDirectSubclassOf( - ParameterizedType possibleSubtype, InterfaceType type) { + ParameterizedType possibleSubtype, + InterfaceType type, + ) { if (possibleSubtype is InterfaceType) { InterfaceType? superclass = possibleSubtype.superclass; // Even if `superclass == null` (superclass of Object), the equality @@ -3445,8 +3885,10 @@ class BuilderImplementation { /// `null`. Uses [errorReporter] to report an error if it is a subclass /// of [focusClass] which is not a direct subclass of [focusClass], /// because such a class is not supported as a Reflector. - Future _getReflectableAnnotation( - ElementAnnotation elementAnnotation, InterfaceElement focusClass) async { + Future _getReflectableAnnotation( + ElementAnnotation elementAnnotation, + InterfaceElement2 focusClass, + ) async { if (elementAnnotation.element == null) { // This behavior is based on the assumption that a `null` element means // "there is no annotation here". @@ -3458,7 +3900,9 @@ class BuilderImplementation { /// which is intended to refer to the class Reflectable defined /// in package:reflectable/reflectable.dart. Future checkInheritance( - ParameterizedType type, InterfaceType classReflectable) async { + ParameterizedType type, + InterfaceType classReflectable, + ) async { if (!_isSubclassOf(type, classReflectable)) { // Not a subclass of [classReflectable] at all. return false; @@ -3467,31 +3911,34 @@ class BuilderImplementation { // Instance of [classReflectable], or of indirect subclass // of [classReflectable]: Not supported, report an error. await _severe( - errors.metadataNotDirectSubclass, elementAnnotation.element); + errors.metadataNotDirectSubclass, + elementAnnotation.element2, + ); return false; } // A direct subclass of [classReflectable], all OK. return true; } - Element? element = elementAnnotation.element; - if (element is ConstructorElement) { - DartType enclosingType = _typeForReflectable(element.enclosingElement); + Element2? element = elementAnnotation.element2; + if (element is ConstructorElement2) { + DartType enclosingType = _typeForReflectable(element.enclosingElement2); DartType focusClassType = _typeForReflectable(focusClass); - bool isOk = enclosingType is ParameterizedType && + bool isOk = + enclosingType is ParameterizedType && focusClassType is InterfaceType && await checkInheritance(enclosingType, focusClassType); if (isOk) { if (enclosingType is InterfaceType) { - return enclosingType.element; + return enclosingType.element3; } else { return null; } } else { return null; } - } else if (element is PropertyAccessorElement) { - PropertyInducingElement? variable = element.variable2; + } else if (element is PropertyAccessorElement2) { + PropertyInducingElement2? variable = element.variable3; DartObject? constantValue = variable?.computeConstantValue(); // Handle errors during evaluation. In general `constantValue` is // null for (1) non-const variables, (2) variables without an @@ -3503,13 +3950,14 @@ class BuilderImplementation { if (constantValue == null) return null; DartType? constantValueType = constantValue.type; DartType focusClassType = _typeForReflectable(focusClass); - bool isOk = constantValueType is ParameterizedType && + bool isOk = + constantValueType is ParameterizedType && focusClassType is InterfaceType && await checkInheritance(constantValueType, focusClassType); - // When `isOK` is true, result.value.type.element is a InterfaceElement. + // When `isOK` is true, result.value.type.element is a InterfaceElement2. if (isOk) { if (constantValueType is InterfaceType) { - return constantValueType.element; + return constantValueType.element3; } else { return null; } @@ -3519,16 +3967,20 @@ class BuilderImplementation { } // Otherwise [element] is some other construct which is not supported. await _fine( - 'Ignoring metadata in a form ($elementAnnotation) ' - 'which is not yet supported.', - elementAnnotation.element); + 'Ignoring metadata in a form ($elementAnnotation) ' + 'which is not yet supported.', + elementAnnotation.element2, + ); return null; } /// Adds a warning to the log, using the source code location of `target` /// to identify the relevant location where the error occurs. - Future _warn(WarningKind kind, String message, - [Element? target]) async { + Future _warn( + WarningKind kind, + String message, [ + Element2? target, + ]) async { if (_warningEnabled(kind)) { if (target != null) { log.warning(await _formatDiagnosticMessage(message, target, _resolver)); @@ -3542,30 +3994,33 @@ class BuilderImplementation { /// annotations on imports of [reflectableLibrary], and record the arguments /// of these annotations by modifying [globalPatterns] and [globalMetadata]. Future _findGlobalQuantifyAnnotations( - Map> globalPatterns, - Map> globalMetadata) async { - LibraryElement reflectableLibrary = + Map> globalPatterns, + Map> globalMetadata, + ) async { + LibraryElement2 reflectableLibrary = _librariesByName['reflectable.reflectable']!; - LibraryElement capabilityLibrary = + LibraryElement2 capabilityLibrary = _librariesByName['reflectable.capability']!; - ClassElement reflectableClass = reflectableLibrary.getClass('Reflectable')!; + ClassElement2 reflectableClass = + reflectableLibrary.getClass2('Reflectable')!; InterfaceType typeType = reflectableLibrary.typeProvider.typeType; - InterfaceElement typeTypeClass = typeType.element; + InterfaceElement2 typeTypeClass = typeType.element3; - ConstructorElement globalQuantifyCapabilityConstructor = capabilityLibrary - .getClass('GlobalQuantifyCapability')! - .getNamedConstructor('')!; - ConstructorElement globalQuantifyMetaCapabilityConstructor = + ConstructorElement2 globalQuantifyCapabilityConstructor = + capabilityLibrary + .getClass2('GlobalQuantifyCapability')! + .getNamedConstructor2('')!; + ConstructorElement2 globalQuantifyMetaCapabilityConstructor = capabilityLibrary - .getClass('GlobalQuantifyMetaCapability')! - .getNamedConstructor('')!; + .getClass2('GlobalQuantifyMetaCapability')! + .getNamedConstructor2('')!; - for (LibraryElement library in _libraries) { - List imports = library.libraryImports; + for (LibraryElement2 library in _libraries) { + List imports = library.importedLibraries; for (var import in imports) { - if (import.importedLibrary?.id != reflectableLibrary.id) continue; - for (ElementAnnotation metadatum in import.metadata) { - Element? metadatumElement = metadatum.element?.declaration; + if (import.id != reflectableLibrary.id) continue; + for (ElementAnnotation metadatum in import.metadata2.annotations) { + Element2? metadatumElement = metadatum.element2?.baseElement; if (metadatumElement == globalQuantifyCapabilityConstructor) { DartObject? value = _getEvaluatedMetadatum(metadatum); if (value != null) { @@ -3573,29 +4028,33 @@ class BuilderImplementation { value.getField('classNamePattern')?.toStringValue(); DartType? valueType = value.getField('(super)')?.getField('reflector')?.type; - InterfaceElement? reflector = - valueType is InterfaceType ? valueType.element : null; + InterfaceElement2? reflector = + valueType is InterfaceType ? valueType.element3 : null; if (reflector == null) { await _warn( - WarningKind.badSuperclass, - 'The reflector must be a direct subclass of Reflectable.', - metadatumElement); + WarningKind.badSuperclass, + 'The reflector must be a direct subclass of Reflectable.', + metadatumElement, + ); continue; } else { InterfaceType? reflectorSupertype = reflector.supertype; if (reflectorSupertype is InterfaceType && reflectorSupertype.element != reflectableClass) { await _warn( - WarningKind.badSuperclass, - 'The reflector must be a direct subclass of ' - 'Reflectable. Found ${reflector.name}.', - metadatumElement); + WarningKind.badSuperclass, + 'The reflector must be a direct subclass of ' + 'Reflectable. Found ${reflector.name3}.', + metadatumElement, + ); continue; } } globalPatterns .putIfAbsent( - RegExp(pattern ?? ''), () => []) + RegExp(pattern ?? ''), + () => [], + ) .add(reflector); } } else if (metadatumElement == @@ -3604,9 +4063,9 @@ class BuilderImplementation { if (constantValue != null) { DartObject? metadataType = constantValue.getField('metadataType'); DartType? metadataFieldType = metadataType?.toTypeValue(); - InterfaceElement? metadataFieldValue = + InterfaceElement2? metadataFieldValue = metadataFieldType is InterfaceType - ? metadataFieldType.element + ? metadataFieldType.element3 : null; DartType? metadataTypeType = metadataType?.type; if (metadataFieldValue == null) { @@ -3620,17 +4079,21 @@ class BuilderImplementation { await _warn(WarningKind.badMetadata, message, metadatumElement); continue; } - DartType? reflectorType = constantValue - .getField('(super)') - ?.getField('reflector') - ?.type; - InterfaceElement? reflector = - reflectorType is InterfaceType ? reflectorType.element : null; + DartType? reflectorType = + constantValue + .getField('(super)') + ?.getField('reflector') + ?.type; + InterfaceElement2? reflector = + reflectorType is InterfaceType + ? reflectorType.element3 + : null; if (reflector == null) { await _warn( - WarningKind.badSuperclass, - 'The reflector must be a direct subclass of Reflectable.', - metadatumElement); + WarningKind.badSuperclass, + 'The reflector must be a direct subclass of Reflectable.', + metadatumElement, + ); continue; } else { InterfaceType? reflectorSupertype = reflector.supertype; @@ -3638,15 +4101,16 @@ class BuilderImplementation { reflectorSupertype is InterfaceType && reflectorSupertype.element != reflectableClass) { await _warn( - WarningKind.badSuperclass, - 'The reflector must be a direct subclass of ' - 'Reflectable. Found ${reflector.name}.', - metadatumElement); + WarningKind.badSuperclass, + 'The reflector must be a direct subclass of ' + 'Reflectable. Found ${reflector.name3}.', + metadatumElement, + ); continue; } } globalMetadata - .putIfAbsent(metadataFieldValue, () => []) + .putIfAbsent(metadataFieldValue, () => []) .add(reflector); } } @@ -3663,11 +4127,14 @@ class BuilderImplementation { /// update accordingly. The rest of the builder can then rely on every /// reflector class to be well-formed, and just have assertions rather than /// emitting error messages about it. - Future _isReflectorClass(InterfaceElement potentialReflectorClass, - InterfaceElement reflectableClass) async { + Future _isReflectorClass( + InterfaceElement2 potentialReflectorClass, + InterfaceElement2 reflectableClass, + ) async { if (potentialReflectorClass == reflectableClass) return false; - DartType potentialReflectorType = - _typeForReflectable(potentialReflectorClass); + DartType potentialReflectorType = _typeForReflectable( + potentialReflectorClass, + ); DartType reflectableType = _typeForReflectable(reflectableClass); if (potentialReflectorType is! ParameterizedType || reflectableType is! InterfaceType) { @@ -3683,38 +4150,42 @@ class BuilderImplementation { // of [classReflectable]: Not supported, warn about having such a class // at all, even though we don't know for sure it is used as a reflector. await _warn( - WarningKind.badReflectorClass, - 'An indirect subclass of `Reflectable` will not work as a reflector.' - '\nIt is not recommended to have such a class at all.', - potentialReflectorClass); + WarningKind.badReflectorClass, + 'An indirect subclass of `Reflectable` will not work as a reflector.' + '\nIt is not recommended to have such a class at all.', + potentialReflectorClass, + ); return false; } Future constructorFail() async { await _severe( - 'A reflector class must have exactly one ' - 'constructor which is `const`, has \n' - 'the empty name, takes zero arguments, and ' - 'uses at most one superinitializer.\n' - 'Please correct `$potentialReflectorClass` to match this.', - potentialReflectorClass); + 'A reflector class must have exactly one ' + 'constructor which is `const`, has \n' + 'the empty name, takes zero arguments, and ' + 'uses at most one superinitializer.\n' + 'Please correct `$potentialReflectorClass` to match this.', + potentialReflectorClass, + ); } - if (potentialReflectorClass.constructors.length != 1) { + if (potentialReflectorClass.constructors2.length != 1) { // We "own" the direct subclasses of `Reflectable` so when they are // malformed as reflector classes we raise an error. await constructorFail(); return false; } - ConstructorElement constructor = potentialReflectorClass.constructors[0]; - if (constructor.parameters.isNotEmpty || !constructor.isConst) { + ConstructorElement2 constructor = potentialReflectorClass.constructors2[0]; + if (constructor.formalParameters.isNotEmpty || !constructor.isConst) { // We still "own" `potentialReflectorClass`. await constructorFail(); return false; } - AstNode? constructorDeclarationNode = - await _getDeclarationAst(constructor, _resolver); + AstNode? constructorDeclarationNode = await _getDeclarationAst( + constructor, + _resolver, + ); if (constructorDeclarationNode == null || constructorDeclarationNode is! ConstructorDeclaration) { return false; @@ -3742,49 +4213,59 @@ class BuilderImplementation { /// and it is used to decide whether it is possible to import other libraries /// from the entry point. If the transformation is guaranteed to have no /// effect the return value is [null]. - Future<_ReflectionWorld?> _computeWorld(LibraryElement reflectableLibrary, - LibraryElement entryPoint, AssetId dataId) async { - final InterfaceElement? classReflectable = + Future<_ReflectionWorld?> _computeWorld( + LibraryElement2 reflectableLibrary, + LibraryElement2 entryPoint, + AssetId dataId, + ) async { + final InterfaceElement2? classReflectable = await _findReflectableInterfaceElement(reflectableLibrary); - final allReflectors = {}; + final allReflectors = {}; // If class `Reflectable` is absent the transformation must be a no-op. if (classReflectable == null) { - log.info('Ignoring entry point $entryPoint that does not ' - 'include the class `Reflectable`.'); + log.info( + 'Ignoring entry point $entryPoint that does not ' + 'include the class `Reflectable`.', + ); return null; } // The world will be built from the library arguments plus these two. - final domains = {}; + final domains = {}; final importCollector = _ImportCollector(); // Maps each pattern to the list of reflectors associated with it via // a [GlobalQuantifyCapability]. - var globalPatterns = >{}; + var globalPatterns = >{}; // Maps each [Type] to the list of reflectors associated with it via // a [GlobalQuantifyMetaCapability]. - var globalMetadata = >{}; + var globalMetadata = >{}; - final LibraryElement? capabilityLibrary = + final LibraryElement2? capabilityLibrary = _librariesByName['reflectable.capability']; if (capabilityLibrary == null) { - log.info('Ignoring entry point $entryPoint that does not ' - 'include the library reflectable.capability'); + log.info( + 'Ignoring entry point $entryPoint that does not ' + 'include the library reflectable.capability', + ); return null; } /// Gets the [ReflectorDomain] associated with [reflector], or creates /// it if none exists. Future<_ReflectorDomain> getReflectorDomain( - InterfaceElement reflector) async { + InterfaceElement2 reflector, + ) async { _ReflectorDomain? domain = domains[reflector]; if (domain == null) { - LibraryElement reflectorLibrary = reflector.library; - _Capabilities capabilities = - await _capabilitiesOf(capabilityLibrary, reflector); + LibraryElement2 reflectorLibrary = reflector.library2; + _Capabilities capabilities = await _capabilitiesOf( + capabilityLibrary, + reflector, + ); assert(await _isImportableLibrary(reflectorLibrary, dataId, _resolver)); importCollector._addLibrary(reflectorLibrary); domain = _ReflectorDomain(_resolver, dataId, reflector, capabilities); @@ -3795,7 +4276,9 @@ class BuilderImplementation { /// Adds [library] to the supported libraries of [reflector]. Future addLibrary( - LibraryElement library, InterfaceElement reflector) async { + LibraryElement2 library, + InterfaceElement2 reflector, + ) async { _ReflectorDomain domain = await getReflectorDomain(reflector); if (domain._capabilities._supportsLibraries) { assert(await _isImportableLibrary(library, dataId, _resolver)); @@ -3808,21 +4291,23 @@ class BuilderImplementation { /// [reflector]; also adds the enclosing library of [type] to the /// supported libraries. Future addClassDomain( - InterfaceElement type, InterfaceElement reflector) async { + InterfaceElement2 type, + InterfaceElement2 reflector, + ) async { if (!await _isImportable(type, dataId, _resolver)) { - await _fine('Ignoring unrepresentable class ${type.name}', type); + await _fine('Ignoring unrepresentable class ${type.name3}', type); } else { _ReflectorDomain domain = await getReflectorDomain(reflector); if (!domain._classes.contains(type)) { if (type is MixinApplication && type.isMixinApplication) { // Iterate over all mixins in most-general-first order (so with // `class C extends B with M1, M2..` we visit `M1` then `M2`. - InterfaceElement superclass = type.supertype!.element; + InterfaceElement2 superclass = type.supertype!.element3; for (InterfaceType mixin in type.mixins) { - InterfaceElement mixinElement = mixin.element; + InterfaceElement2 mixinElement = mixin.element3; MixinApplication? subClass = mixin == type.mixins.last ? type : null; - String? name = subClass == null ? null : type.name; + String? name = subClass == null ? null : type.name3!; var mixinApplication = MixinApplication( name, superclass, @@ -3836,7 +4321,7 @@ class BuilderImplementation { } else { domain._classes.add(type); } - await addLibrary(type.library, reflector); + await addLibrary(type.library2, reflector); // We need to ensure that the [importCollector] has indeed added // `type.library` (if we have no library capability `addLibrary` will // not do that), because it may be needed in import directives in the @@ -3845,7 +4330,7 @@ class BuilderImplementation { // TODO(eernst) clarify: Maybe the following statement could be moved // out of the `if` in `addLibrary` such that we don't have to have // an extra copy of it here. - importCollector._addLibrary(type.library); + importCollector._addLibrary(type.library2); } } } @@ -3855,9 +4340,11 @@ class BuilderImplementation { /// [GlobalQuantifyMetaCapability] or [GlobalQuantifyCapability]. /// [qualifiedName] is the name of the library or class annotated by /// [metadata]. - Future> getReflectors( - String? qualifiedName, List metadata) async { - var result = []; + Future> getReflectors( + String? qualifiedName, + List metadata, + ) async { + var result = []; for (ElementAnnotation metadatum in metadata) { DartObject? value = _getEvaluatedMetadatum(metadatum); @@ -3867,10 +4354,10 @@ class BuilderImplementation { if (value != null) { DartType? valueType = value.type; if (valueType is InterfaceType) { - List? reflectors = + List? reflectors = globalMetadata[valueType.element]; if (reflectors != null) { - for (InterfaceElement reflector in reflectors) { + for (InterfaceElement2 reflector in reflectors) { result.add(reflector); } } @@ -3878,18 +4365,22 @@ class BuilderImplementation { } // Test if the annotation is a reflector. - InterfaceElement? reflector = - await _getReflectableAnnotation(metadatum, classReflectable); + InterfaceElement2? reflector = await _getReflectableAnnotation( + metadatum, + classReflectable, + ); if (reflector != null) result.add(reflector); } // Add All reflectors associated with a // pattern, via GlobalQuantifyCapability, that matches the qualified // name of the class or library. - globalPatterns - .forEach((RegExp pattern, List reflectors) { + globalPatterns.forEach(( + RegExp pattern, + List reflectors, + ) { if (qualifiedName != null && pattern.hasMatch(qualifiedName)) { - for (InterfaceElement reflector in reflectors) { + for (InterfaceElement2 reflector in reflectors) { result.add(reflector); } } @@ -3903,34 +4394,45 @@ class BuilderImplementation { // Visits all libraries and all classes in the given entry point, // gets their reflectors, and adds them to the domain of that // reflector. - for (LibraryElement library in _libraries) { - for (InterfaceElement reflector - in await getReflectors(library.name, library.metadata)) { + for (LibraryElement2 library in _libraries) { + for (InterfaceElement2 reflector in await getReflectors( + library.name3, + library.metadata2.annotations, + )) { assert(await _isImportableLibrary(library, dataId, _resolver)); await addLibrary(library, reflector); } - for (CompilationUnitElement unit in library.units) { - for (InterfaceElement type in unit.classes) { - for (InterfaceElement reflector - in await getReflectors(_qualifiedName(type), type.metadata)) { - await addClassDomain(type, reflector); + for (LibraryFragment fragment in library.fragments) { + for (ClassFragment classFragment in fragment.classes2) { + for (InterfaceElement2 reflector in await getReflectors( + _qualifiedName(classFragment.element), + classFragment.metadata2.annotations, + )) { + await addClassDomain(classFragment.element, reflector); } - if (!allReflectors.contains(type) && - await _isReflectorClass(type, classReflectable)) { - allReflectors.add(type); + if (!allReflectors.contains(classFragment.element) && + await _isReflectorClass( + classFragment.element, + classReflectable, + )) { + allReflectors.add(classFragment.element); } } - for (EnumElement type in unit.enums) { - for (InterfaceElement reflector - in await getReflectors(_qualifiedName(type), type.metadata)) { - await addClassDomain(type, reflector); + for (EnumFragment type in fragment.enums2) { + for (InterfaceElement2 reflector in await getReflectors( + _qualifiedName(type.element), + type.metadata2.annotations, + )) { + await addClassDomain(type.element, reflector); } // An enum is never a reflector class, hence no `_isReflectorClass`. } - for (FunctionElement function in unit.functions) { - for (InterfaceElement reflector in await getReflectors( - _qualifiedFunctionName(function), function.metadata)) { + for (TopLevelFunctionElement function in fragment.functions) { + for (InterfaceElement2 reflector in await getReflectors( + _qualifiedFunctionName(function), + function.metadata2.annotations, + )) { // We just add the library here, the function itself will be // supported using `invoke` and `declarations` of that library // mirror. @@ -3940,14 +4442,18 @@ class BuilderImplementation { } } - var usedReflectors = {}; + var usedReflectors = {}; for (_ReflectorDomain domain in domains.values) { usedReflectors.add(domain._reflector); } - for (InterfaceElement reflector - in allReflectors.difference(usedReflectors)) { - await _warn(WarningKind.unusedReflector, - 'This reflector does not match anything', reflector); + for (InterfaceElement2 reflector in allReflectors.difference( + usedReflectors, + )) { + await _warn( + WarningKind.unusedReflector, + 'This reflector does not match anything', + reflector, + ); // Ensure that there is an empty domain for `reflector` in `domains`. await getReflectorDomain(reflector); } @@ -3957,13 +4463,14 @@ class BuilderImplementation { // defined during construction, so `_world` is non-final and left unset by // the constructor, and we need to close the cycle here. var world = _ReflectionWorld( - _resolver, - _libraries, - dataId, - domains.values.toList(), - reflectableLibrary, - entryPoint, - importCollector); + _resolver, + _libraries, + dataId, + domains.values.toList(), + reflectableLibrary, + entryPoint, + importCollector, + ); for (_ReflectorDomain domain in domains.values) { domain._world = world; } @@ -3973,12 +4480,15 @@ class BuilderImplementation { /// Returns the [ReflectCapability] denoted by the given initializer /// [expression] reporting diagnostic messages for [messageTarget]. Future _capabilityOfExpression( - LibraryElement capabilityLibrary, - Expression expression, - LibraryElement containingLibrary, - Element messageTarget) async { - DartObject? constant = - await _evaluateConstant(containingLibrary, expression); + LibraryElement2 capabilityLibrary, + Expression expression, + LibraryElement2 containingLibrary, + Element2 messageTarget, + ) async { + DartObject? constant = await _evaluateConstant( + containingLibrary, + expression, + ); if (constant is! DartObject) { await _severe( @@ -4005,20 +4515,25 @@ class BuilderImplementation { // be in the given `capabilityLibrary` (because we could never know // how to interpret the meaning of a user-written capability class, so // users cannot write their own capability classes). - InterfaceElement dartTypeElement = (dartType as InterfaceType).element; - if (dartTypeElement is! ClassElement) { + InterfaceElement2 dartTypeElement = (dartType as InterfaceType).element3; + if (dartTypeElement is! ClassElement2) { String typeString = dartType.getDisplayString(); await _severe( - errors.applyTemplate( - errors.superArgumentNonClass, {'type': typeString}), - dartTypeElement); + errors.applyTemplate(errors.superArgumentNonClass, { + 'type': typeString, + }), + dartTypeElement, + ); return null; // Error default. } - if (dartTypeElement.library != capabilityLibrary) { + if (dartTypeElement.library2 != capabilityLibrary) { await _severe( - errors.applyTemplate(errors.superArgumentWrongLibrary, - {'library': '$capabilityLibrary', 'element': '$dartTypeElement'}), - dartTypeElement); + errors.applyTemplate(errors.superArgumentWrongLibrary, { + 'library': '$capabilityLibrary', + 'element': '$dartTypeElement', + }), + dartTypeElement, + ); return null; // Error default. } @@ -4026,15 +4541,19 @@ class BuilderImplementation { /// NamePatternCapability. Future extractNamePattern(DartObject constant) async { DartObject? constantSuper = constant.getField('(super)'); - DartObject? constantSuperNamePattern = - constantSuper?.getField('namePattern'); + DartObject? constantSuperNamePattern = constantSuper?.getField( + 'namePattern', + ); String? constantSuperNamePatternString = constantSuperNamePattern?.toStringValue(); if (constantSuper == null || constantSuperNamePattern == null || constantSuperNamePatternString == null) { - await _warn(WarningKind.badNamePattern, - 'Could not extract namePattern from capability.', messageTarget); + await _warn( + WarningKind.badNamePattern, + 'Could not extract namePattern from capability.', + messageTarget, + ); return null; } return constantSuperNamePatternString; @@ -4043,27 +4562,32 @@ class BuilderImplementation { /// Extracts the metadata property from an instance of a subclass of /// MetadataCapability represented by [constant], reporting any diagnostic /// messages as referring to [messageTarget]. - Future extractMetadata(DartObject constant) async { + Future extractMetadata(DartObject constant) async { DartObject? constantSuper = constant.getField('(super)'); - DartObject? constantSuperMetadataType = - constantSuper?.getField('metadataType'); + DartObject? constantSuperMetadataType = constantSuper?.getField( + 'metadataType', + ); if (constantSuper == null || constantSuperMetadataType == null) { - await _warn(WarningKind.badMetadata, - 'Could not extract metadata type from capability.', messageTarget); + await _warn( + WarningKind.badMetadata, + 'Could not extract metadata type from capability.', + messageTarget, + ); return null; } DartType? metadataFieldType = constantSuperMetadataType.toTypeValue(); Object? metadataFieldValue = metadataFieldType is InterfaceType ? metadataFieldType.element : null; - if (metadataFieldValue is InterfaceElement) return metadataFieldValue; + if (metadataFieldValue is InterfaceElement2) return metadataFieldValue; await _warn( - WarningKind.badMetadata, - 'Metadata specification in capability must be a class `Type`.', - messageTarget); + WarningKind.badMetadata, + 'Metadata specification in capability must be a class `Type`.', + messageTarget, + ); return null; } - switch (dartTypeElement.name) { + switch (dartTypeElement.name3) { case 'NameCapability': return ec.nameCapability; case 'ClassifyCapability': @@ -4087,7 +4611,7 @@ class BuilderImplementation { if (namePattern == null) return null; return ec.InstanceInvokeCapability(namePattern); case 'InstanceInvokeMetaCapability': - InterfaceElement? metadata = await extractMetadata(constant); + InterfaceElement2? metadata = await extractMetadata(constant); if (metadata == null) return null; return ec.InstanceInvokeMetaCapability(metadata); case 'StaticInvokeCapability': @@ -4095,7 +4619,7 @@ class BuilderImplementation { if (namePattern == null) return null; return ec.StaticInvokeCapability(namePattern); case 'StaticInvokeMetaCapability': - InterfaceElement? metadata = await extractMetadata(constant); + InterfaceElement2? metadata = await extractMetadata(constant); if (metadata == null) return null; return ec.StaticInvokeMetaCapability(metadata); case 'TopLevelInvokeCapability': @@ -4103,7 +4627,7 @@ class BuilderImplementation { if (namePattern == null) return null; return ec.TopLevelInvokeCapability(namePattern); case 'TopLevelInvokeMetaCapability': - InterfaceElement? metadata = await extractMetadata(constant); + InterfaceElement2? metadata = await extractMetadata(constant); if (metadata == null) return null; return ec.TopLevelInvokeMetaCapability(metadata); case 'NewInstanceCapability': @@ -4111,7 +4635,7 @@ class BuilderImplementation { if (namePattern == null) return null; return ec.NewInstanceCapability(namePattern); case 'NewInstanceMetaCapability': - InterfaceElement? metadata = await extractMetadata(constant); + InterfaceElement2? metadata = await extractMetadata(constant); if (metadata == null) return null; return ec.NewInstanceMetaCapability(metadata); case 'TypeCapability': @@ -4121,7 +4645,7 @@ class BuilderImplementation { if (namePattern == null) return null; return ec.InvokingCapability(namePattern); case 'InvokingMetaCapability': - InterfaceElement? metadata = await extractMetadata(constant); + InterfaceElement2? metadata = await extractMetadata(constant); if (metadata == null) return null; return ec.InvokingMetaCapability(metadata); case 'TypingCapability': @@ -4132,26 +4656,32 @@ class BuilderImplementation { return ec.subtypeQuantifyCapability; case 'SuperclassQuantifyCapability': DartObject? constantUpperBound = constant.getField('upperBound'); - DartObject? constantExcludeUpperBound = - constant.getField('excludeUpperBound'); + DartObject? constantExcludeUpperBound = constant.getField( + 'excludeUpperBound', + ); if (constantUpperBound == null || constantExcludeUpperBound == null) { return null; } DartType constantUpperBoundType = constantUpperBound.toTypeValue()!; if (constantUpperBoundType is! InterfaceType) return null; - return ec.SuperclassQuantifyCapability(constantUpperBoundType.element, - excludeUpperBound: constantExcludeUpperBound.toBoolValue()!); + return ec.SuperclassQuantifyCapability( + constantUpperBoundType.element3, + excludeUpperBound: constantExcludeUpperBound.toBoolValue()!, + ); case 'TypeAnnotationQuantifyCapability': DartObject? constantTransitive = constant.getField('transitive'); if (constantTransitive == null) return null; return ec.TypeAnnotationQuantifyCapability( - transitive: constantTransitive.toBoolValue()!); + transitive: constantTransitive.toBoolValue()!, + ); case '_CorrespondingSetterQuantifyCapability': return ec.correspondingSetterQuantifyCapability; case '_AdmitSubtypeCapability': // TODO(eernst) implement: support for the admit subtype feature. await _severe( - '_AdmitSubtypeCapability not yet supported!', messageTarget); + '_AdmitSubtypeCapability not yet supported!', + messageTarget, + ); return ec.admitSubtypeCapability; default: // We have checked that [element] is declared in 'capability.dart', @@ -4167,8 +4697,10 @@ class BuilderImplementation { /// Returns the list of Capabilities given as a superinitializer by the /// reflector. Future<_Capabilities> _capabilitiesOf( - LibraryElement capabilityLibrary, InterfaceElement reflector) async { - List constructors = reflector.constructors; + LibraryElement2 capabilityLibrary, + InterfaceElement2 reflector, + ) async { + List constructors = reflector.constructors2; // Well-formedness for each reflector class is checked by // `_isReflectorClass`, so we do not report errors here. But errors will @@ -4179,7 +4711,7 @@ class BuilderImplementation { if (constructors.length != 1) { return _Capabilities([]); } - ConstructorElement constructorElement = constructors[0]; + ConstructorElement2 constructorElement = constructors[0]; if (!constructorElement.isConst || !constructorElement.isDefaultConstructor) { return _Capabilities([]); @@ -4200,9 +4732,11 @@ class BuilderImplementation { return _Capabilities([]); } if (initializers.length != 1) { - await _severe('Encountered a reflector whose constructor has ' - 'an unexpected initializer list. It must be of the form ' - '`super(...)` or `super.fromList(...)`'); + await _severe( + 'Encountered a reflector whose constructor has ' + 'an unexpected initializer list. It must be of the form ' + '`super(...)` or `super.fromList(...)`', + ); return _Capabilities([]); } @@ -4215,19 +4749,27 @@ class BuilderImplementation { } Future capabilityOfExpression( - Expression expression) async { + Expression expression, + ) async { return await _capabilityOfExpression( - capabilityLibrary, expression, reflector.library, constructorElement); + capabilityLibrary, + expression, + reflector.library2, + constructorElement, + ); } Future capabilityOfCollectionElement( - CollectionElement collectionElement) async { + CollectionElement collectionElement, + ) async { if (collectionElement is Expression) { return await capabilityOfExpression(collectionElement); } else { - await _severe('Not supported! ' - 'Encountered a collection element which is not an expression: ' - '$collectionElement'); + await _severe( + 'Not supported! ' + 'Encountered a collection element which is not an expression: ' + '$collectionElement', + ); return null; } } @@ -4253,9 +4795,11 @@ class BuilderImplementation { Expression listLiteral = arguments[0]; var capabilities = []; if (listLiteral is! ListLiteral) { - await _severe('Encountered a reflector using super.fromList(...) ' - 'with an argument that is not a list literal, ' - 'which is not supported'); + await _severe( + 'Encountered a reflector using super.fromList(...) ' + 'with an argument that is not a list literal, ' + 'which is not supported', + ); } else { for (CollectionElement collectionElement in listLiteral.elements) { ec.ReflectCapability? currentCapability = @@ -4270,21 +4814,26 @@ class BuilderImplementation { /// reflection data according to [world], and invoke the main of /// [entrypointLibrary] located at [originalEntryPointFilename]. The code is /// generated to be located at [generatedLibraryId]. - Future _generateNewEntryPoint(_ReflectionWorld world, - AssetId generatedLibraryId, String originalEntryPointFilename) async { + Future _generateNewEntryPoint( + _ReflectionWorld world, + AssetId generatedLibraryId, + String originalEntryPointFilename, + ) async { // Notice it is important to generate the code before printing the // imports because generating the code can add further imports. String code = await world.generateCode(); var imports = []; - for (LibraryElement library in world.importCollector._libraries) { - Uri uri = library == world.entryPointLibrary - ? Uri.parse(originalEntryPointFilename) - : await _getImportUri(library, _resolver, generatedLibraryId); + for (LibraryElement2 library in world.importCollector._libraries) { + Uri uri = + library == world.entryPointLibrary + ? Uri.parse(originalEntryPointFilename) + : await _getImportUri(library, _resolver, generatedLibraryId); String prefix = world.importCollector._getPrefix(library); if (prefix.isNotEmpty) { - imports - .add("import '$uri' as ${prefix.substring(0, prefix.length - 1)};"); + imports.add( + "import '$uri' as ${prefix.substring(0, prefix.length - 1)};", + ); } } imports.sort(); @@ -4316,7 +4865,7 @@ void initializeReflectable() { } '''; if (_formatted) { - var formatter = DartFormatter(); + var formatter = DartFormatter(languageVersion: Version(3, 0, 0)); result = formatter.format(result); } return result; @@ -4325,13 +4874,14 @@ void initializeReflectable() { /// Perform the build which produces a set of statically generated /// mirror classes, as requested using reflectable capabilities. Future buildMirrorLibrary( - Resolver resolver, - AssetId inputId, - AssetId generatedLibraryId, - LibraryElement inputLibrary, - List visibleLibraries, - bool formatted, - List suppressedWarnings) async { + Resolver resolver, + AssetId inputId, + AssetId generatedLibraryId, + LibraryElement2 inputLibrary, + List visibleLibraries, + bool formatted, + List suppressedWarnings, + ) async { _formatted = formatted; _suppressedWarnings = suppressedWarnings; @@ -4339,16 +4889,18 @@ void initializeReflectable() { _resolver = resolver; _libraries = visibleLibraries; - for (LibraryElement library in _libraries) { - _librariesByName[library.name] = library; + for (LibraryElement2 library in _libraries) { + _librariesByName[library.name3!] = library; } - LibraryElement? reflectableLibrary = + LibraryElement2? reflectableLibrary = _librariesByName['reflectable.reflectable']; if (reflectableLibrary == null) { // Stop and let the original source pass through without changes. - log.info('Ignoring entry point $inputId that does not ' - "include the library 'package:reflectable/reflectable.dart'"); + log.info( + 'Ignoring entry point $inputId that does not ' + "include the library 'package:reflectable/reflectable.dart'", + ); if (const bool.fromEnvironment('reflectable.pause.at.exit')) { _processedEntryPointCount++; } @@ -4361,8 +4913,11 @@ void initializeReflectable() { print("Starting build for '$inputId'."); } - _ReflectionWorld? world = - await _computeWorld(reflectableLibrary, inputLibrary, inputId); + _ReflectionWorld? world = await _computeWorld( + reflectableLibrary, + inputLibrary, + inputId, + ); if (world == null) { // Errors have already been reported during `_computeWorld`. if (const bool.fromEnvironment('reflectable.pause.at.exit')) { @@ -4378,7 +4933,10 @@ void initializeReflectable() { return '// No output from reflectable, there is no `main`.'; } else { String outputContents = await _generateNewEntryPoint( - world, generatedLibraryId, path.basename(inputId.path)); + world, + generatedLibraryId, + path.basename(inputId.path), + ); if (const bool.fromEnvironment('reflectable.pause.at.exit')) { _processedEntryPointCount++; } @@ -4396,9 +4954,10 @@ void initializeReflectable() { } /// Returns a constant resolved version of the given [libraryElement]. - Future _resolvedLibraryOf( - LibraryElement libraryElement) async { - for (LibraryElement libraryElement2 in _libraries) { + Future _resolvedLibraryOf( + LibraryElement2 libraryElement, + ) async { + for (LibraryElement2 libraryElement2 in _libraries) { if (libraryElement.identifier == libraryElement2.identifier) { return libraryElement2; } @@ -4409,12 +4968,13 @@ void initializeReflectable() { } } -bool _accessorIsntImplicitGetterOrSetter(PropertyAccessorElement accessor) { - return !accessor.isSynthetic || (!accessor.isGetter && !accessor.isSetter); +bool _accessorIsntImplicitGetterOrSetter(PropertyAccessorElement2 accessor) { + return !accessor.isSynthetic || + (accessor is! GetterElement && accessor is! SetterElement); } -bool _executableIsntImplicitGetterOrSetter(ExecutableElement executable) { - if (executable is PropertyAccessorElement) { +bool _executableIsntImplicitGetterOrSetter(ExecutableElement2 executable) { + if (executable is PropertyAccessorElement2) { return _accessorIsntImplicitGetterOrSetter(executable); } else { return true; @@ -4423,21 +4983,21 @@ bool _executableIsntImplicitGetterOrSetter(ExecutableElement executable) { /// Returns an integer encoding of the kind and attributes of the given /// class. -int _classDescriptor(InterfaceElement element) { +int _classDescriptor(InterfaceElement2 element) { int result = constants.clazz; if (element.isPrivate) result |= constants.privateAttribute; if (element.isSynthetic) result |= constants.syntheticAttribute; - if (element is MixinElement || - element is ClassElement && element.isAbstract) { + if (element is MixinElement2 || + element is ClassElement2 && element.isAbstract) { result |= constants.abstractAttribute; } - if (element is EnumElement) result |= constants.enumAttribute; + if (element is EnumElement2) result |= constants.enumAttribute; if (element is MixinApplication) { result |= constants.nonNullableAttribute; return result; } DartType thisType = element.thisType; - LibraryElement library = element.library; + LibraryElement2 library = element.library2; if (library.typeSystem.isNullable(thisType)) { result |= constants.nullableAttribute; } @@ -4449,7 +5009,7 @@ int _classDescriptor(InterfaceElement element) { /// Returns an integer encoding of the kind and attributes of the given /// variable. -int _topLevelVariableDescriptor(TopLevelVariableElement element) { +int _topLevelVariableDescriptor(TopLevelVariableElement2 element) { int result = constants.field; if (element.isPrivate) result |= constants.privateAttribute; if (element.isSynthetic) result |= constants.syntheticAttribute; @@ -4468,13 +5028,13 @@ int _topLevelVariableDescriptor(TopLevelVariableElement element) { if (declaredType is DynamicType) result |= constants.dynamicAttribute; if (declaredType is NeverType) result |= constants.neverAttribute; if (declaredType is InterfaceType) { - Element? elementType = declaredType.element; - if (elementType is InterfaceElement) { + Element2? elementType = declaredType.element3; + if (elementType is InterfaceElement2) { result |= constants.classTypeAttribute; } result |= constants.topLevelAttribute; } - LibraryElement library = element.library; + LibraryElement2 library = element.library2; if (library.typeSystem.isNullable(declaredType)) { result |= constants.nullableAttribute; } @@ -4486,7 +5046,7 @@ int _topLevelVariableDescriptor(TopLevelVariableElement element) { /// Returns an integer encoding of the kind and attributes of the given /// field. -int _fieldDescriptor(FieldElement element) { +int _fieldDescriptor(FieldElement2 element) { int result = constants.field; if (element.isPrivate) result |= constants.privateAttribute; if (element.isSynthetic) result |= constants.syntheticAttribute; @@ -4505,15 +5065,15 @@ int _fieldDescriptor(FieldElement element) { if (declaredType is DynamicType) result |= constants.dynamicAttribute; if (declaredType is NeverType) result |= constants.neverAttribute; if (declaredType is InterfaceType) { - Element? elementType = declaredType.element; - if (elementType is InterfaceElement) { + Element2? elementType = declaredType.element3; + if (elementType is InterfaceElement2) { result |= constants.classTypeAttribute; if (elementType.typeParameters.isNotEmpty) { result |= constants.genericTypeAttribute; } } } - LibraryElement library = element.library; + LibraryElement2 library = element.library2; if (library.typeSystem.isNullable(declaredType)) { result |= constants.nullableAttribute; } @@ -4525,7 +5085,7 @@ int _fieldDescriptor(FieldElement element) { /// Returns an integer encoding of the kind and attributes of the given /// parameter. -int _parameterDescriptor(ParameterElement element) { +int _parameterDescriptor(FormalParameterElement element) { int result = constants.parameter; if (element.isPrivate) result |= constants.privateAttribute; if (element.isSynthetic) result |= constants.syntheticAttribute; @@ -4541,15 +5101,15 @@ int _parameterDescriptor(ParameterElement element) { if (declaredType is DynamicType) result |= constants.dynamicAttribute; if (declaredType is NeverType) result |= constants.neverAttribute; if (declaredType is InterfaceType) { - Element? elementType = declaredType.element; - if (elementType is InterfaceElement) { + Element2? elementType = declaredType.element3; + if (elementType is InterfaceElement2) { result |= constants.classTypeAttribute; if (elementType.typeParameters.isNotEmpty) { result |= constants.genericTypeAttribute; } } } - LibraryElement? library = element.library; + LibraryElement2? library = element.library2; if (library != null) { if (library.typeSystem.isNullable(declaredType)) { result |= constants.nullableAttribute; @@ -4563,10 +5123,10 @@ int _parameterDescriptor(ParameterElement element) { /// Returns an integer encoding of the kind and attributes of the given /// method/constructor/getter/setter. -int _declarationDescriptor(ExecutableElement element) { +int _declarationDescriptor(ExecutableElement2 element) { var result = 0; - void handleReturnType(ExecutableElement element) { + void handleReturnType(ExecutableElement2 element) { DartType returnType = element.returnType; if (returnType is VoidType) { result |= constants.voidReturnTypeAttribute; @@ -4578,8 +5138,8 @@ int _declarationDescriptor(ExecutableElement element) { result |= constants.neverReturnTypeAttribute; } if (returnType is InterfaceType) { - Element? elementReturnType = returnType.element; - if (elementReturnType is InterfaceElement) { + Element2? elementReturnType = returnType.element3; + if (elementReturnType is InterfaceElement2) { result |= constants.classReturnTypeAttribute; if (elementReturnType.typeParameters.isNotEmpty) { result |= constants.genericReturnTypeAttribute; @@ -4588,24 +5148,24 @@ int _declarationDescriptor(ExecutableElement element) { } } - if (element is PropertyAccessorElement) { - result |= element.isGetter ? constants.getter : constants.setter; + if (element is PropertyAccessorElement2) { + result |= element is GetterElement ? constants.getter : constants.setter; handleReturnType(element); - } else if (element is ConstructorElement) { + } else if (element is ConstructorElement2) { if (element.isFactory) { result |= constants.factoryConstructor; } else { result |= constants.generativeConstructor; } if (element.isConst) result |= constants.constAttribute; - if (element.redirectedConstructor != null) { + if (element.redirectedConstructor2 != null) { result |= constants.redirectingConstructorAttribute; } - } else if (element is MethodElement) { + } else if (element is MethodElement2) { result |= constants.method; handleReturnType(element); } else { - assert(element is FunctionElement); + assert(element is TopLevelFunctionElement); result |= constants.function; handleReturnType(element); } @@ -4614,19 +5174,20 @@ int _declarationDescriptor(ExecutableElement element) { if (element.isSynthetic) result |= constants.syntheticAttribute; // TODO(eernst): Work around issue in analyzer, cf. #39051. // When resolved, only the inner `if` is needed. - if (element is! ConstructorElement) { + if (element is! ConstructorElement2) { if (element.isAbstract) result |= constants.abstractAttribute; } - if (element.enclosingElement is! InterfaceElement) { + if (element.enclosingElement2 is! InterfaceElement2) { result |= constants.topLevelAttribute; } return result; } -Future _nameOfConstructor(ConstructorElement element) async { - String name = element.name == '' - ? element.enclosingElement.name - : '${element.enclosingElement.name}.${element.name}'; +Future _nameOfConstructor(ConstructorElement2 element) async { + String name = + element.name3 == '' + ? element.enclosingElement2.name3! + : '${element.enclosingElement2.name3}.${element.name3}'; if (_isPrivateName(name)) { await _severe('Cannot access private name $name', element); } @@ -4649,14 +5210,15 @@ String _formatAsMap(Iterable parts) => '{${parts.join(', ')}}'; /// value when evaluated in the generated file as the given [expression] /// would evaluate to in [originatingLibrary]. Future _extractConstantCode( - Expression expression, - _ImportCollector importCollector, - AssetId generatedLibraryId, - Resolver resolver) async { + Expression expression, + _ImportCollector importCollector, + AssetId generatedLibraryId, + Resolver resolver, +) async { Future typeAnnotationHelper(TypeAnnotation typeName) async { DartType? interfaceType = typeName.type; if (interfaceType is InterfaceType) { - LibraryElement library = interfaceType.element.library; + LibraryElement2 library = interfaceType.element3.library2; String prefix = importCollector._getPrefix(library); return '$prefix$typeName'; } else { @@ -4678,9 +5240,11 @@ Future _extractConstantCode( elements.add(await helper(subExpression)); } else { // TODO(eernst) implement: `if` and `spread` elements of list. - await _severe('Not yet supported! ' - 'Encountered list literal element which is not an expression: ' - '$collectionElement'); + await _severe( + 'Not yet supported! ' + 'Encountered list literal element which is not an expression: ' + '$collectionElement', + ); elements.add(''); } } @@ -4690,8 +5254,9 @@ Future _extractConstantCode( return 'const ${_formatAsDynamicList(elements)}'; } else { assert(expressionTypeArguments.arguments.length == 1); - String typeArgument = - await typeAnnotationHelper(expressionTypeArguments.arguments[0]); + String typeArgument = await typeAnnotationHelper( + expressionTypeArguments.arguments[0], + ); return 'const <$typeArgument>${_formatAsDynamicList(elements)}'; } } else if (expression is SetOrMapLiteral) { @@ -4704,9 +5269,11 @@ Future _extractConstantCode( elements.add('$key: $value'); } else { // TODO(eernst) implement: `if` and `spread` elements of a map. - await _severe('Not yet supported! ' - 'Encountered map literal element which is not a map entry: ' - '$collectionElement'); + await _severe( + 'Not yet supported! ' + 'Encountered map literal element which is not a map entry: ' + '$collectionElement', + ); elements.add(''); } } @@ -4716,10 +5283,12 @@ Future _extractConstantCode( return 'const ${_formatAsMap(elements)}'; } else { assert(expressionTypeArguments.arguments.length == 2); - String keyType = - await typeAnnotationHelper(expressionTypeArguments.arguments[0]); - String valueType = - await typeAnnotationHelper(expressionTypeArguments.arguments[1]); + String keyType = await typeAnnotationHelper( + expressionTypeArguments.arguments[0], + ); + String valueType = await typeAnnotationHelper( + expressionTypeArguments.arguments[1], + ); return 'const <$keyType, $valueType>${_formatAsMap(elements)}'; } } else if (expression.isSet) { @@ -4730,9 +5299,11 @@ Future _extractConstantCode( elements.add(await helper(subExpression)); } else { // TODO(eernst) implement: `if` and `spread` elements of a set. - await _severe('Not yet supported! ' - 'Encountered set literal element which is not an expression: ' - '$collectionElement'); + await _severe( + 'Not yet supported! ' + 'Encountered set literal element which is not an expression: ' + '$collectionElement', + ); elements.add(''); } } @@ -4742,8 +5313,9 @@ Future _extractConstantCode( return 'const ${_formatAsDynamicSet(elements)}'; } else { assert(expressionTypeArguments.arguments.length == 1); - String typeArgument = - await typeAnnotationHelper(expressionTypeArguments.arguments[0]); + String typeArgument = await typeAnnotationHelper( + expressionTypeArguments.arguments[0], + ); return 'const <$typeArgument>${_formatAsDynamicSet(elements)}'; } } else { @@ -4752,14 +5324,19 @@ Future _extractConstantCode( } else if (expression is InstanceCreationExpression) { String constructor = expression.constructorName.toSource(); if (_isPrivateName(constructor)) { - await _severe('Cannot access private name $constructor, ' - 'needed for expression $expression'); + await _severe( + 'Cannot access private name $constructor, ' + 'needed for expression $expression', + ); return ''; } - LibraryElement libraryOfConstructor = - expression.constructorName.staticElement!.library; + LibraryElement2 libraryOfConstructor = + expression.constructorName.element!.library2; if (await _isImportableLibrary( - libraryOfConstructor, generatedLibraryId, resolver)) { + libraryOfConstructor, + generatedLibraryId, + resolver, + )) { importCollector._addLibrary(libraryOfConstructor); String prefix = importCollector._getPrefix(libraryOfConstructor); // TODO(sigurdm) implement: Named arguments. @@ -4770,24 +5347,29 @@ Future _extractConstantCode( String arguments = argumentList.join(', '); // TODO(sigurdm) feature: Type arguments. if (_isPrivateName(constructor)) { - await _severe('Cannot access private name $constructor, ' - 'needed for expression $expression'); + await _severe( + 'Cannot access private name $constructor, ' + 'needed for expression $expression', + ); return ''; } return 'const $prefix$constructor($arguments)'; } else { - await _severe('Cannot access library $libraryOfConstructor, ' - 'needed for expression $expression'); + await _severe( + 'Cannot access library $libraryOfConstructor, ' + 'needed for expression $expression', + ); return ''; } } else if (expression is Identifier) { if (Identifier.isPrivateName(expression.name)) { - Element? staticElement = expression.staticElement; - if (staticElement is PropertyAccessorElement) { - VariableElement? variable = staticElement.variable2; - AstNode? variableDeclaration = variable != null - ? await _getDeclarationAst(variable, resolver) - : null; + Element2? staticElement = expression.element; + if (staticElement is PropertyAccessorElement2) { + VariableElement2? variable = staticElement.variable3; + AstNode? variableDeclaration = + variable != null + ? await _getDeclarationAst(variable, resolver) + : null; if (variableDeclaration == null || variableDeclaration is! VariableDeclaration) { await _severe('Cannot handle private identifier $expression'); @@ -4800,35 +5382,44 @@ Future _extractConstantCode( return ''; } } else { - Element? element = expression.staticElement; + Element2? element = expression.element; if (element == null) { // TODO(eernst): This can occur; but how could `expression` be // unresolved? Issue 173. - await _fine('Encountered unresolved identifier $expression' - ' in constant; using null'); + await _fine( + 'Encountered unresolved identifier $expression' + ' in constant; using null', + ); return 'null'; - } else if (element.library == null) { - return '${element.name}'; + } else if (element.library2 == null) { + return '${element.name3}'; } else { - LibraryElement? elementLibrary = element.library; + LibraryElement2? elementLibrary = element.library2; if (elementLibrary != null && await _isImportableLibrary( - elementLibrary, generatedLibraryId, resolver)) { + elementLibrary, + generatedLibraryId, + resolver, + )) { importCollector._addLibrary(elementLibrary); String prefix = importCollector._getPrefix(elementLibrary); - Element? enclosingElement = element.enclosingElement; - if (enclosingElement is InterfaceElement) { - prefix += '${enclosingElement.name}.'; + Element2? enclosingElement = element.enclosingElement2; + if (enclosingElement is InterfaceElement2) { + prefix += '${enclosingElement.name3}.'; } - String? elementName = element.name; + String? elementName = element.name3; if (elementName != null && _isPrivateName(elementName)) { - await _severe('Cannot access private name $elementName, ' - 'needed for expression $expression'); + await _severe( + 'Cannot access private name $elementName, ' + 'needed for expression $expression', + ); } return '$prefix$elementName'; } else { - await _severe('Cannot access library $elementLibrary, ' - 'needed for expression $expression'); + await _severe( + 'Cannot access library $elementLibrary, ' + 'needed for expression $expression', + ); return ''; } } @@ -4861,11 +5452,19 @@ Future _extractConstantCode( return 'identical($a, $b)'; } else if (expression is NamedExpression) { String value = await _extractConstantCode( - expression.expression, importCollector, generatedLibraryId, resolver); + expression.expression, + importCollector, + generatedLibraryId, + resolver, + ); return '${expression.name} $value'; } else if (expression is FunctionReference) { String function = await _extractConstantCode( - expression.function, importCollector, generatedLibraryId, resolver); + expression.function, + importCollector, + generatedLibraryId, + resolver, + ); TypeArgumentList? expressionTypeArguments = expression.typeArguments; if (expressionTypeArguments == null) { return function; @@ -4873,20 +5472,23 @@ Future _extractConstantCode( var typeArguments = []; for (TypeAnnotation expressionTypeArgument in expressionTypeArguments.arguments) { - String typeArgument = - await typeAnnotationHelper(expressionTypeArgument); + String typeArgument = await typeAnnotationHelper( + expressionTypeArgument, + ); typeArguments.add(typeArgument); } return '$function<${typeArguments.join(', ')}>'; } } else { - assert(expression is IntegerLiteral || - expression is BooleanLiteral || - expression is StringLiteral || - expression is NullLiteral || - expression is SymbolLiteral || - expression is DoubleLiteral || - expression is TypedLiteral); + assert( + expression is IntegerLiteral || + expression is BooleanLiteral || + expression is StringLiteral || + expression is NullLiteral || + expression is SymbolLiteral || + expression is DoubleLiteral || + expression is TypedLiteral, + ); return expression.toSource(); } } @@ -4913,13 +5515,14 @@ const Set sdkLibraryNames = { 'ui', 'web_audio', 'web_gl', - 'web_sql' + 'web_sql', }; // Helper for _extractMetadataCode. CompilationUnit? _definingCompilationUnit( - ResolvedLibraryResult resolvedLibrary) { - CompilationUnitElement definingUnit = + ResolvedLibraryResult resolvedLibrary, +) { + LibraryFragment definingUnit = resolvedLibrary.element.definingCompilationUnit; List units = resolvedLibrary.units; for (var unit in units) { @@ -4942,9 +5545,9 @@ NodeList? _getLibraryMetadata(CompilationUnit? unit) { } // Helper for _extractMetadataCode. -NodeList? _getOtherMetadata(AstNode? node, Element element) { +NodeList? _getOtherMetadata(AstNode? node, Element2 element) { if (node == null) { - // `node` can be null with members of subclasses of `Element` from + // `node` can be null with members of subclasses of `Element2` from // 'dart:html'. return null; } @@ -4960,7 +5563,7 @@ NodeList? _getOtherMetadata(AstNode? node, Element element) { // Similarly, the `element.node` of a [TopLevelVariableElement] is a // [VariableDeclaration] nested in a [VariableDeclarationList] nested in a // [TopLevelVariableDeclaration], which stores the metadata. - if (element is FieldElement || element is TopLevelVariableElement) { + if (element is FieldElement2 || element is TopLevelVariableElement2) { node = node.parent!.parent!; } @@ -4979,11 +5582,15 @@ NodeList? _getOtherMetadata(AstNode? node, Element element) { /// Returns a String with the code used to build the metadata of [element]. /// /// Also adds any necessary imports to [importCollector]. -Future _extractMetadataCode(Element element, Resolver resolver, - _ImportCollector importCollector, AssetId dataId) async { +Future _extractMetadataCode( + Element2 element, + Resolver resolver, + _ImportCollector importCollector, + AssetId dataId, +) async { // Synthetic accessors do not have metadata. Only their associated fields. - if ((element is PropertyAccessorElement || - element is ConstructorElement || + if ((element is PropertyAccessorElement2 || + element is ConstructorElement2 || element is MixinApplication) && element.isSynthetic) { return 'const []'; @@ -4991,19 +5598,23 @@ Future _extractMetadataCode(Element element, Resolver resolver, // TODO(eernst): 'dart:*' is not considered valid. To survive, we return // the empty metadata for elements from 'dart:*'. Issue 173. - if (_isPlatformLibrary(element.library)) { + if (_isPlatformLibrary(element.library2)) { return 'const []'; } NodeList? metadata; - ResolvedLibraryResult? resolvedLibrary = - await _getResolvedLibrary(element.library!, resolver); - if (element is LibraryElement && resolvedLibrary != null) { + ResolvedLibraryResult? resolvedLibrary = await _getResolvedLibrary( + element.library2!, + resolver, + ); + if (element is LibraryElement2 && resolvedLibrary != null) { metadata = _getLibraryMetadata(_definingCompilationUnit(resolvedLibrary)); } else { // The declaration is null if the element is synthetic. metadata = _getOtherMetadata( - resolvedLibrary?.getElementDeclaration(element)?.node, element); + resolvedLibrary?.getElementDeclaration(element)?.node, + element, + ); } if (metadata == null || metadata.isEmpty) return 'const []'; @@ -5011,7 +5622,7 @@ Future _extractMetadataCode(Element element, Resolver resolver, for (Annotation annotationNode in metadata) { // TODO(sigurdm) diagnostic: Emit a warning/error if the element is not // in the global public scope of the library. - Element? annotationNodeElement = annotationNode.element; + Element2? annotationNodeElement = annotationNode.element2; if (annotationNodeElement == null) { // Some internal constants (mainly in dart:html) cannot be resolved by // the analyzer. Ignore them. @@ -5030,18 +5641,26 @@ Future _extractMetadataCode(Element element, Resolver resolver, await _fine('Ignoring unrepresentable metadata $annotationNode', element); continue; } - LibraryElement annotationLibrary = annotationNodeElement.library!; + LibraryElement2 annotationLibrary = annotationNodeElement.library2!; importCollector._addLibrary(annotationLibrary); String prefix = importCollector._getPrefix(annotationLibrary); ArgumentList? annotationNodeArguments = annotationNode.arguments; if (annotationNodeArguments != null) { // A const constructor. - String name = - await _extractNameWithoutPrefix(annotationNode.name, element); + String name = await _extractNameWithoutPrefix( + annotationNode.name, + element, + ); var argumentList = []; for (Expression argument in annotationNodeArguments.arguments) { - argumentList.add(await _extractConstantCode( - argument, importCollector, dataId, resolver)); + argumentList.add( + await _extractConstantCode( + argument, + importCollector, + dataId, + resolver, + ), + ); } String arguments = argumentList.join(', '); if (_isPrivateName(name)) { @@ -5052,10 +5671,14 @@ Future _extractMetadataCode(Element element, Resolver resolver, // A field reference. if (_isPrivateName(annotationNode.name.name)) { await _severe( - 'Cannot access private name ${annotationNode.name}', element); + 'Cannot access private name ${annotationNode.name}', + element, + ); } - String name = - await _extractNameWithoutPrefix(annotationNode.name, element); + String name = await _extractNameWithoutPrefix( + annotationNode.name, + element, + ); if (_isPrivateName(name)) { await _severe('Cannot access private name $name', element); } @@ -5069,7 +5692,9 @@ Future _extractMetadataCode(Element element, Resolver resolver, /// Extract the plain name from [identifier] by stripping off the /// library import prefix at front, if any. Future _extractNameWithoutPrefix( - Identifier identifier, Element errorTarget) async { + Identifier identifier, + Element2 errorTarget, +) async { String name; if (identifier is SimpleIdentifier) { name = identifier.token.lexeme; @@ -5077,7 +5702,7 @@ Future _extractNameWithoutPrefix( // The identifier is of the form `p.id` where `p` is a library // prefix, or it is on the form `C.id` where `C` is a class and // `id` a named constructor. - if (identifier.prefix.staticElement is PrefixElement) { + if (identifier.prefix.element is PrefixElement2) { // We will replace the library prefix by the appropriate prefix for // code in the generated library, so we omit the prefix specified in // client code. @@ -5087,8 +5712,10 @@ Future _extractNameWithoutPrefix( name = identifier.name; } } else { - await _severe('This kind of identifier is not yet supported: $identifier', - errorTarget); + await _severe( + 'This kind of identifier is not yet supported: $identifier', + errorTarget, + ); name = identifier.name; } return name; @@ -5097,14 +5724,21 @@ Future _extractNameWithoutPrefix( /// Returns the top level variables declared in the given [libraryElement], /// filtering them such that the returned ones are those that are supported /// by [capabilities]. -Iterable _extractDeclaredVariables(Resolver resolver, - LibraryElement libraryElement, _Capabilities capabilities) sync* { - for (CompilationUnitElement unit in libraryElement.units) { - for (TopLevelVariableElement variable in unit.topLevelVariables) { +Iterable _extractDeclaredVariables( + Resolver resolver, + LibraryElement2 libraryElement, + _Capabilities capabilities, +) sync* { + for (LibraryFragment fragment in libraryElement.fragments) { + for (TopLevelVariableElement2 variable in fragment.topLevelVariables2) { if (variable.isPrivate || variable.isSynthetic) continue; // TODO(eernst) clarify: Do we want to subsume variables under invoke? - if (capabilities.supportsTopLevelInvoke(variable.library.typeSystem, - variable.name, variable.metadata, null)) { + if (capabilities.supportsTopLevelInvoke( + variable.library2.typeSystem, + variable.name3!, + variable.metadata2.annotations, + null, + )) { yield variable; } } @@ -5114,13 +5748,21 @@ Iterable _extractDeclaredVariables(Resolver resolver, /// Returns the top level functions declared in the given [libraryElement], /// filtering them such that the returned ones are those that are supported /// by [capabilities]. -Iterable _extractDeclaredFunctions(Resolver resolver, - LibraryElement libraryElement, _Capabilities capabilities) sync* { - for (CompilationUnitElement unit in libraryElement.units) { - for (FunctionElement function in unit.functions) { +Iterable _extractDeclaredFunctions( + Resolver resolver, + LibraryElement2 libraryElement, + _Capabilities capabilities, +) sync* { + for (LibraryFragment fragment in libraryElement.fragments) { + for (TopLevelFunctionFragment fragment in fragment.functions2) { + final function = fragment.element; if (function.isPrivate) continue; - if (capabilities.supportsTopLevelInvoke(function.library.typeSystem, - function.name, function.metadata, null)) { + if (capabilities.supportsTopLevelInvoke( + function.library2.typeSystem, + function.name3!, + function.metadata2.annotations, + null, + )) { yield function; } } @@ -5129,250 +5771,422 @@ Iterable _extractDeclaredFunctions(Resolver resolver, /// Returns the parameters declared in the given [declaredFunctions] as well /// as the setters from the given [accessors]. -Iterable _extractDeclaredFunctionParameters( - Resolver resolver, - Iterable declaredFunctions, - Iterable accessors) { - var result = []; - for (FunctionElement declaredFunction in declaredFunctions) { - result.addAll(declaredFunction.parameters); +Iterable _extractDeclaredFunctionParameters( + Resolver resolver, + Iterable declaredFunctions, + Iterable accessors, +) { + var result = []; + for (TopLevelFunctionElement declaredFunction in declaredFunctions) { + result.addAll(declaredFunction.formalParameters); } - for (ExecutableElement accessor in accessors) { - if (accessor is PropertyAccessorElement && accessor.isSetter) { - result.addAll(accessor.parameters); + for (ExecutableElement2 accessor in accessors) { + if (accessor is SetterElement) { + result.addAll(accessor.formalParameters); } } return result; } -typedef CapabilityChecker = bool Function( - TypeSystem, - String methodName, - Iterable metadata, - Iterable? getterMetadata); +typedef CapabilityChecker = + bool Function( + TypeSystem, + String methodName, + Iterable metadata, + Iterable? getterMetadata, + ); /// Returns the declared fields in the given [interfaceElement], filtered such /// that the returned ones are the ones that are supported by [capabilities]. -Iterable _extractDeclaredFields(Resolver resolver, - InterfaceElement interfaceElement, _Capabilities capabilities) { - return interfaceElement.fields.where((FieldElement field) { +Iterable _extractDeclaredFields( + Resolver resolver, + InterfaceElement2 interfaceElement, + _Capabilities capabilities, +) { + return interfaceElement.fields2.where((FieldElement2 field) { if (field.isPrivate) return false; - CapabilityChecker capabilityChecker = field.isStatic - ? capabilities.supportsStaticInvoke - : capabilities.supportsInstanceInvoke; + CapabilityChecker capabilityChecker = + field.isStatic + ? capabilities.supportsStaticInvoke + : capabilities.supportsInstanceInvoke; return !field.isSynthetic && - capabilityChecker(interfaceElement.library.typeSystem, field.name, - field.metadata, null); + capabilityChecker( + interfaceElement.library2.typeSystem, + field.name3!, + field.metadata2.annotations, + null, + ); }); } /// Returns the declared methods in the given [interfaceElement], filtered such /// that the returned ones are the ones that are supported by [capabilities]. -Iterable _extractDeclaredMethods(Resolver resolver, - InterfaceElement interfaceElement, _Capabilities capabilities) { - return interfaceElement.methods.where((MethodElement method) { +Iterable _extractDeclaredMethods( + Resolver resolver, + InterfaceElement2 interfaceElement, + _Capabilities capabilities, +) { + return interfaceElement.methods2.where((MethodElement2 method) { if (method.isPrivate) return false; - CapabilityChecker capabilityChecker = method.isStatic - ? capabilities.supportsStaticInvoke - : capabilities.supportsInstanceInvoke; + CapabilityChecker capabilityChecker = + method.isStatic + ? capabilities.supportsStaticInvoke + : capabilities.supportsInstanceInvoke; return capabilityChecker( - method.library.typeSystem, method.name, method.metadata, null); + method.library2.typeSystem, + method.name3!, + method.metadata2.annotations, + null, + ); }); } /// Returns the declared parameters in the given [declaredMethods] and /// [declaredConstructors], as well as the ones from the setters in /// [accessors]. -List _extractDeclaredParameters( - Iterable declaredMethods, - Iterable declaredConstructors, - Iterable accessors) { - var result = []; - for (MethodElement declaredMethod in declaredMethods) { - result.addAll(declaredMethod.parameters); +List _extractDeclaredParameters( + Iterable declaredMethods, + Iterable declaredConstructors, + Iterable setters, +) { + var result = []; + for (MethodElement2 declaredMethod in declaredMethods) { + result.addAll(declaredMethod.formalParameters); } - for (ConstructorElement declaredConstructor in declaredConstructors) { - result.addAll(declaredConstructor.parameters); + for (ConstructorElement2 declaredConstructor in declaredConstructors) { + result.addAll(declaredConstructor.formalParameters); } - for (PropertyAccessorElement accessor in accessors) { - if (accessor.isSetter) { - result.addAll(accessor.parameters); - } + for (SetterElement setter in setters) { + result.addAll(setter.formalParameters); } return result; } -/// Returns the accessors from the given [libraryElement], filtered such that +/// Returns the getter from the given [libraryElement], filtered such that +/// the returned ones are the ones that are supported by [capabilities]. +Iterable _extractLibraryGetters( + Resolver resolver, + LibraryElement2 libraryElement, + _Capabilities capabilities, +) sync* { + for (LibraryFragment fragment in libraryElement.fragments) { + for (GetterFragment fragment in fragment.getters) { + final getter = fragment.element as GetterElement; + if (getter.isPrivate) continue; + List metadata; + List? getterMetadata; + if (getter.isSynthetic) { + metadata = getter.variable3?.metadata2.annotations ?? const []; + getterMetadata = metadata; + } else { + metadata = getter.metadata2.annotations; + if (capabilities._impliesCorrespondingSetters && !getter.isSynthetic) { + GetterElement? correspondingGetter = getter.correspondingGetter; + getterMetadata = correspondingGetter?.metadata2.annotations; + } + } + if (capabilities.supportsTopLevelInvoke( + getter.library2.typeSystem, + getter.name3!, + metadata, + getterMetadata, + )) { + yield getter; + } + } + } +} + +/// Returns the setters from the given [libraryElement], filtered such that /// the returned ones are the ones that are supported by [capabilities]. -Iterable _extractLibraryAccessors(Resolver resolver, - LibraryElement libraryElement, _Capabilities capabilities) sync* { - for (CompilationUnitElement unit in libraryElement.units) { - for (PropertyAccessorElement accessor in unit.accessors) { - if (accessor.isPrivate) continue; +Iterable _extractLibrarySetters( + Resolver resolver, + LibraryElement2 libraryElement, + _Capabilities capabilities, +) sync* { + for (LibraryFragment fragment in libraryElement.fragments) { + for (SetterFragment fragment in fragment.setters) { + final setter = fragment.element as SetterElement; + if (setter.isPrivate) continue; List metadata; List? getterMetadata; - if (accessor.isSynthetic) { - metadata = accessor.variable2?.metadata ?? const []; + if (setter.isSynthetic) { + metadata = setter.variable3?.metadata2.annotations ?? const []; getterMetadata = metadata; } else { - metadata = accessor.metadata; - if (capabilities._impliesCorrespondingSetters && - accessor.isSetter && - !accessor.isSynthetic) { - PropertyAccessorElement? correspondingGetter = - accessor.correspondingGetter; - getterMetadata = correspondingGetter?.metadata; + metadata = setter.metadata2.annotations; + if (capabilities._impliesCorrespondingSetters && !setter.isSynthetic) { + GetterElement? correspondingGetter = setter.correspondingGetter; + getterMetadata = correspondingGetter?.metadata2.annotations; } } - if (capabilities.supportsTopLevelInvoke(accessor.library.typeSystem, - accessor.name, metadata, getterMetadata)) { - yield accessor; + if (capabilities.supportsTopLevelInvoke( + setter.library2.typeSystem, + setter.name3!, + metadata, + getterMetadata, + )) { + yield setter; } } } } -/// Returns the [PropertyAccessorElement]s which are the accessors +/// Returns the [GetterElement]s which are the setters /// of the given [interfaceElement], including both the declared ones /// and the implicitly generated ones corresponding to fields. This -/// is the set of accessors that corresponds to the behavioral interface +/// is the set of getters that corresponds to the behavioral interface /// of the corresponding instances, as opposed to the source code oriented /// interface, e.g., `declarations`. But the latter can be computed from -/// here, by filtering out the accessors whose `isSynthetic` is true +/// here, by filtering out the getters whose `isSynthetic` is true, /// and adding the fields. -Iterable _extractAccessors(Resolver resolver, - InterfaceElement interfaceElement, _Capabilities capabilities) { - return interfaceElement.accessors.where((PropertyAccessorElement accessor) { - if (accessor.isPrivate) return false; +Iterable _extractGetters( + Resolver resolver, + InterfaceElement2 interfaceElement, + _Capabilities capabilities, +) { + return interfaceElement.getters2.where((GetterElement getter) { + if (getter.isPrivate) return false; // TODO(eernst) implement: refactor treatment of `getterMetadata` // such that we avoid passing in `null` at all call sites except one, // when we might as well move the processing to that single call site (such // as here, but also in `_extractLibraryAccessors()`, etc). - CapabilityChecker capabilityChecker = accessor.isStatic - ? capabilities.supportsStaticInvoke - : capabilities.supportsInstanceInvoke; - List metadata = accessor.isSynthetic - ? (accessor.variable2?.metadata ?? const []) - : accessor.metadata; + CapabilityChecker capabilityChecker = + getter.isStatic + ? capabilities.supportsStaticInvoke + : capabilities.supportsInstanceInvoke; + List metadata = + getter.isSynthetic + ? (getter.variable3?.metadata2.annotations ?? + const []) + : getter.metadata2.annotations; List? getterMetadata; - if (capabilities._impliesCorrespondingSetters && - accessor.isSetter && - !accessor.isSynthetic) { - PropertyAccessorElement? correspondingGetter = - accessor.correspondingGetter; - getterMetadata = correspondingGetter?.metadata; + return capabilityChecker( + getter.library2.typeSystem, + getter.name3!, + metadata, + getterMetadata, + ); + }); +} + +/// Returns the [SetterElements]s which are the setters of the given +/// [interfaceElement], including both the declared ones and the +/// implicitly generated ones corresponding to mutable fields. This +/// is the set of setters that corresponds to the behavioral interface +/// of the corresponding instances, as opposed to the source code oriented +/// interface, e.g., `declarations`. But the latter can be computed from +/// here, by filtering out the setters whose `isSynthetic` is true, +/// and adding the mutable fields. +Iterable _extractSetters( + Resolver resolver, + InterfaceElement2 interfaceElement, + _Capabilities capabilities, +) { + return interfaceElement.setters2.where((SetterElement setter) { + if (setter.isPrivate) return false; + CapabilityChecker capabilityChecker = + setter.isStatic + ? capabilities.supportsStaticInvoke + : capabilities.supportsInstanceInvoke; + List metadata = + setter.isSynthetic + ? (setter.variable3?.metadata2.annotations ?? + const []) + : setter.metadata2.annotations; + List? getterMetadata; + if (capabilities._impliesCorrespondingSetters && !setter.isSynthetic) { + GetterElement? correspondingGetter = setter.correspondingGetter; + getterMetadata = correspondingGetter?.metadata2.annotations; } return capabilityChecker( - accessor.library.typeSystem, accessor.name, metadata, getterMetadata); + setter.library2.typeSystem, + setter.name3!, + metadata, + getterMetadata, + ); }); } /// Returns the declared constructors from [interfaceElement], filtered such that /// the returned ones are the ones that are supported by [capabilities]. -Iterable _extractDeclaredConstructors( - Resolver resolver, - LibraryElement libraryElement, - InterfaceElement interfaceElement, - _Capabilities capabilities) { - return interfaceElement.constructors.where((ConstructorElement constructor) { +Iterable _extractDeclaredConstructors( + Resolver resolver, + LibraryElement2 libraryElement, + InterfaceElement2 interfaceElement, + _Capabilities capabilities, +) { + return interfaceElement.constructors2.where(( + ConstructorElement2 constructor, + ) { if (constructor.isPrivate) return false; - return capabilities.supportsNewInstance(constructor.library.typeSystem, - constructor.name, constructor.metadata, libraryElement, resolver); + return capabilities.supportsNewInstance( + constructor.library2.typeSystem, + constructor.name3!, + constructor.metadata2.annotations, + libraryElement, + resolver, + ); }); } _LibraryDomain _createLibraryDomain( - LibraryElement library, _ReflectorDomain domain) { - Iterable declaredVariablesOfLibrary = - _extractDeclaredVariables(domain._resolver, library, domain._capabilities) - .toList(); - Iterable declaredFunctionsOfLibrary = - _extractDeclaredFunctions(domain._resolver, library, domain._capabilities) - .toList(); - Iterable accessorsOfLibrary = - _extractLibraryAccessors(domain._resolver, library, domain._capabilities) - .toList(); - Iterable declaredParametersOfLibrary = + LibraryElement2 library, + _ReflectorDomain domain, +) { + Iterable declaredVariablesOfLibrary = + _extractDeclaredVariables( + domain._resolver, + library, + domain._capabilities, + ).toList(); + Iterable declaredFunctionsOfLibrary = + _extractDeclaredFunctions( + domain._resolver, + library, + domain._capabilities, + ).toList(); + Iterable gettersOfLibrary = + _extractLibraryGetters( + domain._resolver, + library, + domain._capabilities, + ).toList(); + Iterable settersOfLibrary = + _extractLibrarySetters( + domain._resolver, + library, + domain._capabilities, + ).toList(); + Iterable declaredParametersOfLibrary = _extractDeclaredFunctionParameters( - domain._resolver, declaredFunctionsOfLibrary, accessorsOfLibrary) - .toList(); + domain._resolver, + declaredFunctionsOfLibrary, + gettersOfLibrary, + ).toList(); return _LibraryDomain( - library, - declaredVariablesOfLibrary, - declaredFunctionsOfLibrary, - declaredParametersOfLibrary, - accessorsOfLibrary, - domain); + library, + declaredVariablesOfLibrary, + declaredFunctionsOfLibrary, + declaredParametersOfLibrary, + gettersOfLibrary, + settersOfLibrary, + domain, + ); } _ClassDomain _createClassDomain( - InterfaceElement type, _ReflectorDomain domain) { + InterfaceElement2 type, + _ReflectorDomain domain, +) { if (type is MixinApplication) { - Iterable declaredFieldsOfClass = _extractDeclaredFields( - domain._resolver, type.mixin, domain._capabilities) - .where((FieldElement e) => !e.isStatic) - .toList(); - Iterable declaredMethodsOfClass = _extractDeclaredMethods( - domain._resolver, type.mixin, domain._capabilities) - .where((MethodElement e) => !e.isStatic) - .toList(); - Iterable declaredAndImplicitAccessorsOfClass = - _extractAccessors(domain._resolver, type.mixin, domain._capabilities) - .toList(); - Iterable declaredConstructorsOfClass = - []; - Iterable declaredParametersOfClass = - _extractDeclaredParameters(declaredMethodsOfClass, - declaredConstructorsOfClass, declaredAndImplicitAccessorsOfClass); + Iterable declaredFieldsOfClass = + _extractDeclaredFields( + domain._resolver, + type.mixin, + domain._capabilities, + ).where((FieldElement2 e) => !e.isStatic).toList(); + Iterable declaredMethodsOfClass = + _extractDeclaredMethods( + domain._resolver, + type.mixin, + domain._capabilities, + ).where((MethodElement2 e) => !e.isStatic).toList(); + Iterable declaredAndImplicitGettersOfClass = + _extractGetters( + domain._resolver, + type.mixin, + domain._capabilities, + ).toList(); + Iterable declaredAndImplicitSettersOfClass = + _extractSetters( + domain._resolver, + type.mixin, + domain._capabilities, + ).toList(); + Iterable declaredConstructorsOfClass = + []; + Iterable declaredParametersOfClass = + _extractDeclaredParameters( + declaredMethodsOfClass, + declaredConstructorsOfClass, + declaredAndImplicitSettersOfClass, + ); return _ClassDomain( - type, - declaredFieldsOfClass, - declaredMethodsOfClass, - declaredParametersOfClass, - declaredAndImplicitAccessorsOfClass, - declaredConstructorsOfClass, - domain); - } - - List declaredFieldsOfClass = - _extractDeclaredFields(domain._resolver, type, domain._capabilities) - .toList(); - List declaredMethodsOfClass = - _extractDeclaredMethods(domain._resolver, type, domain._capabilities) - .toList(); - List declaredAndImplicitAccessorsOfClass = - _extractAccessors(domain._resolver, type, domain._capabilities).toList(); - List declaredConstructorsOfClass = - _extractDeclaredConstructors( - domain._resolver, type.library, type, domain._capabilities) - .toList(); - List declaredParametersOfClass = _extractDeclaredParameters( - declaredMethodsOfClass, - declaredConstructorsOfClass, - declaredAndImplicitAccessorsOfClass); - return _ClassDomain( type, declaredFieldsOfClass, declaredMethodsOfClass, declaredParametersOfClass, - declaredAndImplicitAccessorsOfClass, + declaredAndImplicitGettersOfClass, + declaredAndImplicitSettersOfClass, declaredConstructorsOfClass, - domain); + domain, + ); + } + + List declaredFieldsOfClass = + _extractDeclaredFields( + domain._resolver, + type, + domain._capabilities, + ).toList(); + List declaredMethodsOfClass = + _extractDeclaredMethods( + domain._resolver, + type, + domain._capabilities, + ).toList(); + List declaredAndImplicitGettersOfClass = + _extractGetters(domain._resolver, type, domain._capabilities).toList(); + List declaredAndImplicitSettersOfClass = + _extractSetters(domain._resolver, type, domain._capabilities).toList(); + List declaredConstructorsOfClass = + _extractDeclaredConstructors( + domain._resolver, + type.library2, + type, + domain._capabilities, + ).toList(); + List declaredParametersOfClass = + _extractDeclaredParameters( + declaredMethodsOfClass, + declaredConstructorsOfClass, + declaredAndImplicitSettersOfClass, + ); + return _ClassDomain( + type, + declaredFieldsOfClass, + declaredMethodsOfClass, + declaredParametersOfClass, + declaredAndImplicitGettersOfClass, + declaredAndImplicitSettersOfClass, + declaredConstructorsOfClass, + domain, + ); } /// Answers true iff [element] can be imported into [generatedLibraryId]. // TODO(sigurdm) implement: Make a test that tries to reflect on native/private // classes. Future _isImportable( - Element element, AssetId generatedLibraryId, Resolver resolver) async { + Element2 element, + AssetId generatedLibraryId, + Resolver resolver, +) async { return await _isImportableLibrary( - element.library!, generatedLibraryId, resolver); + element.library2!, + generatedLibraryId, + resolver, + ); } /// Answers true iff [library] can be imported into [generatedLibraryId]. -Future _isImportableLibrary(LibraryElement library, - AssetId generatedLibraryId, Resolver resolver) async { +Future _isImportableLibrary( + LibraryElement2 library, + AssetId generatedLibraryId, + Resolver resolver, +) async { Uri importUri = await _getImportUri(library, resolver, generatedLibraryId); return importUri.scheme != 'dart' || sdkLibraryNames.contains(importUri.path); } @@ -5381,29 +6195,39 @@ Future _isImportableLibrary(LibraryElement library, /// [assetId]. This function returns null if we cannot determine a uri for /// [assetId]. Note that [assetId] may represent a non-importable file such as /// a part. -Future _assetIdToUri(AssetId assetId, AssetId from, - Element messageTarget, Resolver resolver) async { +Future _assetIdToUri( + AssetId assetId, + AssetId from, + Element2 messageTarget, + Resolver resolver, +) async { if (!assetId.path.startsWith('lib/')) { // Cannot do absolute imports of non lib-based assets. if (assetId.package != from.package) { - await _severe(await _formatDiagnosticMessage( + await _severe( + await _formatDiagnosticMessage( 'Attempt to generate non-lib import from different package', messageTarget, - resolver)); + resolver, + ), + ); return null; } return Uri( - path: path.url - .relative(assetId.path, from: path.url.dirname(from.path))) - .toString(); + path: path.url.relative(assetId.path, from: path.url.dirname(from.path)), + ).toString(); } - return Uri.parse('package:${assetId.package}/${assetId.path.substring(4)}') - .toString(); + return Uri.parse( + 'package:${assetId.package}/${assetId.path.substring(4)}', + ).toString(); } Future _getImportUri( - LibraryElement lib, Resolver resolver, AssetId from) async { + LibraryElement2 lib, + Resolver resolver, + AssetId from, +) async { Source source = lib.source; Uri uri = source.uri; if (uri.scheme == 'asset') { @@ -5414,7 +6238,8 @@ Future _getImportUri( String package = uri.pathSegments[0]; String path = uri.path.substring(package.length + 1); return Uri( - path: await _assetIdToUri(AssetId(package, path), from, lib, resolver)); + path: await _assetIdToUri(AssetId(package, path), from, lib, resolver), + ); } if (source is FileSource || source is InSummarySource) { return uri; @@ -5424,16 +6249,16 @@ Future _getImportUri( return Uri.parse('package:${from.package}/${from.path}'); } -/// Modelling a mixin application as a [ClassElement]. +/// Modelling a mixin application as a [ClassElement2]. /// /// We need to model mixin applications separately, because the analyzer uses -/// a model where the superclass (that is, `ClassElement.supertype`) is the +/// a model where the superclass (that is, `ClassElement2.supertype`) is the /// syntactic superclass (for `class C extends B with M..` it is `B`, not the /// mixin application `B with M`) rather than the semantic one (`B with M`). /// The [declaredName] is used in the case `class B = A with M..;` in /// which case it is `B`; with other mixin applications it is [null]. /// We model the superclass of this mixin application with [superclass], -/// which may be a regular [ClassElement] or a [MixinApplication]; the +/// which may be a regular [ClassElement2] or a [MixinApplication]; the /// [mixin] is the class which was applied as a mixin to create this mixin /// application; the [library] is the enclosing library of the mixin /// application; and the [subclass] is the class `C` that caused this mixin @@ -5443,23 +6268,28 @@ Future _getImportUri( /// /// This class is only used to mark the synthetic mixin application classes, /// so most of the class is left unimplemented. -class MixinApplication implements ClassElement { +class MixinApplication implements ClassElementImpl2 { final String? declaredName; - final InterfaceElement superclass; - final InterfaceElement mixin; - final InterfaceElement? subclass; + final InterfaceElement2 superclass; + final InterfaceElement2 mixin; + final InterfaceElement2? subclass; @override - final LibraryElement library; - - MixinApplication(this.declaredName, this.superclass, this.mixin, this.library, - this.subclass); + final LibraryElement2 library; + + MixinApplication( + this.declaredName, + this.superclass, + this.mixin, + this.library, + this.subclass, + ); @override String get name { if (declaredName != null) return declaredName!; if (superclass is MixinApplication) { - return '${superclass.name}, ${_qualifiedName(mixin)}'; + return '${superclass.name3}, ${_qualifiedName(mixin)}'; } else { return '${_qualifiedName(superclass)} with ${_qualifiedName(mixin)}'; } @@ -5484,11 +6314,11 @@ class MixinApplication implements ClassElement { InterfaceType instantiate({ required List typeArguments, required NullabilitySuffix nullabilitySuffix, - }) => - InterfaceTypeImpl( - element: this, - typeArguments: typeArguments, - nullabilitySuffix: nullabilitySuffix); + }) => InterfaceTypeImpl( + element: this, + typeArguments: typeArguments, + nullabilitySuffix: nullabilitySuffix, + ); @override InterfaceType? get supertype { @@ -5526,10 +6356,10 @@ class MixinApplication implements ClassElement { @override bool get isAbstract { - InterfaceElement mixin = this.mixin; + InterfaceElement2 mixin = this.mixin; return !isMixinApplication || - mixin is MixinElement || - mixin is ClassElement && mixin.isAbstract; + mixin is MixinElement2 || + mixin is ClassElement2 && mixin.isAbstract; } // This seems to be the defined behaviour according to dart:mirrors. @@ -5537,7 +6367,7 @@ class MixinApplication implements ClassElement { bool get isPrivate => false; @override - List get typeParameters => []; + List get typeParameters => []; @override ElementKind get kind => ElementKind.CLASS; @@ -5581,20 +6411,22 @@ String _setterNameToGetterName(String name) { return name.substring(0, name.length - 1); } -String _qualifiedName(Element? element) { - LibraryElement? elementLibrary = element?.library; +String _qualifiedName(Element2? element) { + LibraryElement2? elementLibrary = element?.library2; if (element == null || elementLibrary == null) return 'null'; - return '${elementLibrary.name}.${element.name}'; + return '${elementLibrary.name3}.${element.name3}'; } -String _qualifiedFunctionName(FunctionElement functionElement) { - return '${functionElement.library.name}.${functionElement.name}'; +String _qualifiedFunctionName(TopLevelFunctionElement functionElement) { + return '${functionElement.library2.name3}.${functionElement.name3}'; } -String _qualifiedTypeParameterName(TypeParameterElement? typeParameterElement) { +String _qualifiedTypeParameterName( + TypeParameterElement2? typeParameterElement, +) { if (typeParameterElement == null) return 'null'; - return '${_qualifiedName(typeParameterElement.enclosingElement!)}.' - '${typeParameterElement.name}'; + return '${_qualifiedName(typeParameterElement.enclosingElement2!)}.' + '${typeParameterElement.name3}'; } bool _isPrivateName(String name) { @@ -5602,7 +6434,9 @@ bool _isPrivateName(String name) { } Future _evaluateConstant( - LibraryElement library, Expression expression) async { + LibraryElement2 library, + Expression expression, +) async { AstNode? currentUnit = expression.parent; var levels = 0; while (currentUnit != null && @@ -5611,20 +6445,19 @@ Future _evaluateConstant( currentUnit = currentUnit.parent; } if (currentUnit is! CompilationUnit) { - await _severe('Expression `$expression` ' - 'has no enclosing compilation unit.'); + await _severe( + 'Expression `$expression` ' + 'has no enclosing compilation unit.', + ); return null; } - CompilationUnitElement unitElement = currentUnit.declaredElement!; + LibraryFragment unitElement = currentUnit.declaredElement!; Source source = unitElement.source; var libraryElement = unitElement.library as LibraryElementImpl; var errorListener = RecordingErrorListener(); - var errorReporter = ErrorReporter( - errorListener, - source, - ); + var errorReporter = ErrorReporter(errorListener, source); var declaredVariables = DeclaredVariables(); // No variables. var evaluationEngine = ConstantEvaluationEngine( @@ -5671,7 +6504,8 @@ DartObject? _getEvaluatedMetadatum(ElementAnnotation elementAnnotation) => /// Returns the result of evaluating each of the element annotations /// in [metadata] using [_getEvaluatedMetadatum]. Iterable _getEvaluatedMetadata( - Iterable? metadata) { + Iterable? metadata, +) { if (metadata == null) return []; var result = []; for (ElementAnnotation annotation in metadata) { @@ -5687,13 +6521,16 @@ Iterable _getEvaluatedMetadata( /// problem that platform libraries are considered invalid when obtained from /// `getResolvedLibraryByElement`, such that subsequent use will throw. /// Issue 173. -bool _isPlatformLibrary(LibraryElement? libraryElement) => +bool _isPlatformLibrary(LibraryElement2? libraryElement) => libraryElement?.source.uri.scheme == 'dart'; /// Adds a severe error to the log, using the source code location of `target` /// to identify the relevant location where the error occurs. -Future _severe(String message, - [Element? target, Resolver? resolver]) async { +Future _severe( + String message, [ + Element2? target, + Resolver? resolver, +]) async { if (target != null && resolver != null) { log.severe(await _formatDiagnosticMessage(message, target, resolver)); } else { @@ -5703,8 +6540,11 @@ Future _severe(String message, /// Adds a 'fine' message to the log, using the source code location of `target` /// to identify the relevant location where the issue occurs. -Future _fine(String message, - [Element? target, Resolver? resolver]) async { +Future _fine( + String message, [ + Element2? target, + Resolver? resolver, +]) async { if (target != null && resolver != null) { log.fine(await _formatDiagnosticMessage(message, target, resolver)); } else { @@ -5715,25 +6555,31 @@ Future _fine(String message, /// Returns a string containing the given [message] and identifying the /// associated source code location as the location of the given [target]. Future _formatDiagnosticMessage( - String message, Element? target, Resolver resolver) async { - Source? source = target?.source; + String message, + Element2? target, + Resolver resolver, +) async { + Source? source = target?.firstFragment.source; if (source == null) return message; var locationString = ''; - int? nameOffset = target?.nameOffset; + int? nameOffset = target?.firstFragment.nameOffset2; // TODO(eernst): 'dart:*' is not considered valid. To survive, we return // a message with no location info when `element` is from 'dart:*'. Issue 173. - LibraryElement? targetLibrary = target?.library; + LibraryElement2? targetLibrary = target?.library2; if (targetLibrary != null && nameOffset != null && !_isPlatformLibrary(targetLibrary)) { - final ResolvedLibraryResult? resolvedLibrary = - await _getResolvedLibrary(targetLibrary, resolver); + final ResolvedLibraryResult? resolvedLibrary = await _getResolvedLibrary( + targetLibrary, + resolver, + ); if (resolvedLibrary != null) { - final ElementDeclarationResult? targetDeclaration = - resolvedLibrary.getElementDeclaration(target!); + final ElementDeclarationResult? targetDeclaration = resolvedLibrary + .getElementDeclaration2(target!.firstFragment); final CompilationUnit? unit = targetDeclaration?.resolvedUnit?.unit; - final CharacterLocation? location = - unit?.lineInfo.getLocation(nameOffset); + final CharacterLocation? location = unit?.lineInfo.getLocation( + nameOffset, + ); if (location != null) { locationString = '${location.lineNumber}:${location.columnNumber}'; } @@ -5746,16 +6592,20 @@ Future _formatDiagnosticMessage( // (as opposed to stdout and stderr which are swallowed). If given, [target] // is used to indicate a source code location. // ignore:unused_element -Future _emitMessage(String message, - [Element? target, Resolver? resolver]) async { - String formattedMessage = (target != null && resolver != null) - ? await _formatDiagnosticMessage(message, target, resolver) - : message; +Future _emitMessage( + String message, [ + Element2? target, + Resolver? resolver, +]) async { + String formattedMessage = + (target != null && resolver != null) + ? await _formatDiagnosticMessage(message, target, resolver) + : message; log.warning(formattedMessage); } /// Return [AstNode] of declaration of [element], null if synthetic. -Future _getDeclarationAst(Element element, Resolver resolver) => +Future _getDeclarationAst(Element2 element, Resolver resolver) => resolver.astNodeFor(element, resolve: true); /// Return the [ResolvedLibraryResult] of the given [library]. @@ -5764,12 +6614,15 @@ Future _getDeclarationAst(Element element, Resolver resolver) => /// given [library], thus avoiding an `InconsistentAnalysisException` /// which will be thrown if we use `library.session` directly. Future _getResolvedLibrary( - LibraryElement library, Resolver resolver) async { - final LibraryElement freshLibrary = - await resolver.libraryFor(await resolver.assetIdForElement(library)); + LibraryElement2 library, + Resolver resolver, +) async { + final LibraryElement2 freshLibrary = await resolver.libraryFor( + await resolver.assetIdForElement(library), + ); final AnalysisSession freshSession = freshLibrary.session; - final SomeResolvedLibraryResult someResult = - await freshSession.getResolvedLibraryByElement(freshLibrary); + final SomeResolvedLibraryResult someResult = await freshSession + .getResolvedLibraryByElement2(freshLibrary); if (someResult is ResolvedLibraryResult) { return someResult; } else { diff --git a/reflectable/lib/src/element_capability.dart b/reflectable/lib/src/element_capability.dart index 665e483..286fd11 100644 --- a/reflectable/lib/src/element_capability.dart +++ b/reflectable/lib/src/element_capability.dart @@ -19,7 +19,7 @@ library reflectable.src.element_capability; // NB! It is crucial that all changes in '../capabilities.dart' are // performed in the corresponding manner here, and vice versa. -import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/element2.dart'; abstract class ReflectCapability { const ReflectCapability(); @@ -35,7 +35,7 @@ abstract class NamePatternCapability implements ApiReflectCapability { } abstract class MetadataQuantifiedCapability implements ApiReflectCapability { - final InterfaceElement metadataType; + final InterfaceElement2 metadataType; const MetadataQuantifiedCapability(this.metadataType); } @@ -195,10 +195,12 @@ abstract class ReflecteeQuantifyCapability implements ReflectCapability { const subtypeQuantifyCapability = _SubtypeQuantifyCapability(); class SuperclassQuantifyCapability implements ReflecteeQuantifyCapability { - final Element? upperBound; + final Element2? upperBound; final bool excludeUpperBound; - const SuperclassQuantifyCapability(this.upperBound, - {this.excludeUpperBound = false}); + const SuperclassQuantifyCapability( + this.upperBound, { + this.excludeUpperBound = false, + }); } // Note that `null` represents the [ClassElement] for `Object`. @@ -211,8 +213,9 @@ class TypeAnnotationQuantifyCapability implements ReflecteeQuantifyCapability { const typeAnnotationQuantifyCapability = TypeAnnotationQuantifyCapability(); -const typeAnnotationDeepQuantifyCapability = - TypeAnnotationQuantifyCapability(transitive: true); +const typeAnnotationDeepQuantifyCapability = TypeAnnotationQuantifyCapability( + transitive: true, +); const correspondingSetterQuantifyCapability = _CorrespondingSetterQuantifyCapability(); @@ -220,20 +223,20 @@ const correspondingSetterQuantifyCapability = const admitSubtypeCapability = _AdmitSubtypeCapability(); class ImportAttachedCapability { - final Element reflector; + final Element2 reflector; const ImportAttachedCapability(this.reflector); } class GlobalQuantifyCapability extends ImportAttachedCapability { final String classNamePattern; - const GlobalQuantifyCapability(this.classNamePattern, Element reflector) - : super(reflector); + const GlobalQuantifyCapability(this.classNamePattern, Element2 reflector) + : super(reflector); } class GlobalQuantifyMetaCapability extends ImportAttachedCapability { - final Element metadataType; - const GlobalQuantifyMetaCapability(this.metadataType, Element reflector) - : super(reflector); + final Element2 metadataType; + const GlobalQuantifyMetaCapability(this.metadataType, Element2 reflector) + : super(reflector); } class _ReflectedTypeCapability implements DeclarationsCapability { diff --git a/reflectable/lib/src/incompleteness.dart b/reflectable/lib/src/incompleteness.dart index cc112f4..1719b1e 100644 --- a/reflectable/lib/src/incompleteness.dart +++ b/reflectable/lib/src/incompleteness.dart @@ -36,7 +36,8 @@ Never unreachableError(String message) { /// avoid warnings about a missing return problem, and the code may be more /// readable. Never unimplementedError(String message) { - var extendedMessage = '*** Unfortunately, this feature has not yet been ' + var extendedMessage = + '*** Unfortunately, this feature has not yet been ' 'implemented: $message.\n' 'If you wish to ensure that it is prioritized, please report it ' 'on github.com/dart-lang/reflectable.'; diff --git a/reflectable/lib/src/reflectable_base.dart b/reflectable/lib/src/reflectable_base.dart index 2c3fafc..86cea85 100644 --- a/reflectable/lib/src/reflectable_base.dart +++ b/reflectable/lib/src/reflectable_base.dart @@ -54,30 +54,30 @@ class ReflectableBase { /// Const constructor, to enable usage as metadata, allowing for varargs /// style invocation with up to ten arguments. - const ReflectableBase( - [this._cap0, - this._cap1, - this._cap2, - this._cap3, - this._cap4, - this._cap5, - this._cap6, - this._cap7, - this._cap8, - this._cap9]) - : _capabilitiesGivenAsList = false, - _capabilities = null; + const ReflectableBase([ + this._cap0, + this._cap1, + this._cap2, + this._cap3, + this._cap4, + this._cap5, + this._cap6, + this._cap7, + this._cap8, + this._cap9, + ]) : _capabilitiesGivenAsList = false, + _capabilities = null; const ReflectableBase.fromList(this._capabilities) - : _capabilitiesGivenAsList = true, - _cap0 = null, - _cap1 = null, - _cap2 = null, - _cap3 = null, - _cap4 = null, - _cap5 = null, - _cap6 = null, - _cap7 = null, - _cap8 = null, - _cap9 = null; + : _capabilitiesGivenAsList = true, + _cap0 = null, + _cap1 = null, + _cap2 = null, + _cap3 = null, + _cap4 = null, + _cap5 = null, + _cap6 = null, + _cap7 = null, + _cap8 = null, + _cap9 = null; } diff --git a/reflectable/lib/src/reflectable_builder_based.dart b/reflectable/lib/src/reflectable_builder_based.dart index 2d461b5..c253fa4 100644 --- a/reflectable/lib/src/reflectable_builder_based.dart +++ b/reflectable/lib/src/reflectable_builder_based.dart @@ -110,15 +110,16 @@ class ReflectorData { Map? _typeToTypeMirrorCache; ReflectorData( - this.typeMirrors, - this.memberMirrors, - this.parameterMirrors, - this.types, - this.supportedClassCount, - this.getters, - this.setters, - this.libraryMirrors, - this.parameterListShapes); + this.typeMirrors, + this.memberMirrors, + this.parameterMirrors, + this.types, + this.supportedClassCount, + this.getters, + this.setters, + this.libraryMirrors, + this.parameterListShapes, + ); /// Returns a type mirror for the given [type]. /// @@ -135,9 +136,11 @@ class ReflectorData { // Note that [types] corresponds to the prefix of [typeMirrors] which // are class mirrors; [typeMirrors] continues with type variable // mirrors, and they are irrelevant here. - _typeToTypeMirrorCache = typeToTypeMirrorCache = { - for (var i = 0; i < supportedClassCount; ++i) types[i]: typeMirrors[i] - }; + _typeToTypeMirrorCache = + typeToTypeMirrorCache = { + for (var i = 0; i < supportedClassCount; ++i) + types[i]: typeMirrors[i], + }; } typeToTypeMirrorCache[_typeOf()] = VoidMirrorImpl(); typeToTypeMirrorCache[dynamic] = DynamicMirrorImpl(); @@ -154,7 +157,10 @@ class ReflectorData { if (typeMirror is GenericClassMirrorImpl) { if (typeMirror._isGenericRuntimeTypeOf(instance)) { return _createInstantiatedGenericClass( - typeMirror, instance.runtimeType, null); + typeMirror, + instance.runtimeType, + null, + ); } } } @@ -163,7 +169,8 @@ class ReflectorData { } } -const String pleaseInitializeMessage = 'Reflectable has not been initialized.\n' +const String pleaseInitializeMessage = + 'Reflectable has not been initialized.\n' 'Please make sure that the first action taken by your program\n' 'in `main` is to call `initializeReflectable()`.'; @@ -216,7 +223,8 @@ class _InstanceMirrorImpl extends _DataCaching implements InstanceMirror { // type of the reflectee is known. if (!_data.types.contains(reflectee.runtimeType)) { throw NoSuchCapabilityError( - 'Reflecting on un-marked type "${reflectee.runtimeType}"'); + 'Reflecting on un-marked type "${reflectee.runtimeType}"', + ); } } } @@ -229,21 +237,29 @@ class _InstanceMirrorImpl extends _DataCaching implements InstanceMirror { ClassMirror get type { if (!_supportsType) { throw NoSuchCapabilityError( - 'Attempt to get `type` without `TypeCapability`.'); + 'Attempt to get `type` without `TypeCapability`.', + ); } return _type!; } @override - Object? invoke(String methodName, List positionalArguments, - [Map? namedArguments]) { + Object? invoke( + String methodName, + List positionalArguments, [ + Map? namedArguments, + ]) { Never fail() { // It could be a method that exists but the given capabilities rejected // it, it could be a method that does not exist at all, or it could be // a non-conforming argument list shape. In all cases we consider the // invocation to be a capability violation. throw reflectableNoSuchMethodError( - reflectee, methodName, positionalArguments, namedArguments); + reflectee, + methodName, + positionalArguments, + namedArguments, + ); } // Obtain the tear-off closure for the method that we will invoke. @@ -260,11 +276,17 @@ class _InstanceMirrorImpl extends _DataCaching implements InstanceMirror { throw unreachableError('Attempt to `invoke` without class mirrors'); } if (!_type!._checkInstanceParameterListShape( - methodName, positionalArguments.length, namedArguments?.keys)) { + methodName, + positionalArguments.length, + namedArguments?.keys, + )) { fail(); } return Function.apply( - methodTearer(reflectee), positionalArguments, namedArguments); + methodTearer(reflectee), + positionalArguments, + namedArguments, + ); } @override @@ -283,26 +305,29 @@ class _InstanceMirrorImpl extends _DataCaching implements InstanceMirror { @override dynamic delegate(Invocation invocation) { Never fail() { - StringInvocationKind kind = invocation.isGetter - ? StringInvocationKind.getter - : (invocation.isSetter - ? StringInvocationKind.setter - : StringInvocationKind.method); + StringInvocationKind kind = + invocation.isGetter + ? StringInvocationKind.getter + : (invocation.isSetter + ? StringInvocationKind.setter + : StringInvocationKind.method); // TODO(eernst) implement: Pass the de-minified `memberName` string, if // get support for translating arbitrary symbols to strings (the caller // could use `new Symbol(..)` so we cannot assume that this symbol is // known). throw reflectableNoSuchInvokableError( - reflectee, - '${invocation.memberName}', - invocation.positionalArguments, - invocation.namedArguments, - kind); + reflectee, + '${invocation.memberName}', + invocation.positionalArguments, + invocation.namedArguments, + kind, + ); } if (memberSymbolMap == null) { throw NoSuchCapabilityError( - 'Attempt to `delegate` without `delegateCapability`'); + 'Attempt to `delegate` without `delegateCapability`', + ); } String? memberName = memberSymbolMap![invocation.memberName]; if (memberName == null) { @@ -325,8 +350,11 @@ class _InstanceMirrorImpl extends _DataCaching implements InstanceMirror { } return invokeSetter(memberName, invocation.positionalArguments[0]); } else { - return invoke(memberName, invocation.positionalArguments, - invocation.namedArguments); + return invoke( + memberName, + invocation.positionalArguments, + invocation.namedArguments, + ); } } @@ -392,8 +420,9 @@ abstract class ClassMirrorBase extends _DataCaching implements ClassMirror { if (_superinterfaceIndices.length == 1 && _superinterfaceIndices[0] == noCapabilityIndex) { throw NoSuchCapabilityError( - 'Requesting `superinterfaces` of `$qualifiedName` ' - 'without `typeRelationsCapability`'); + 'Requesting `superinterfaces` of `$qualifiedName` ' + 'without `typeRelationsCapability`', + ); } return _superinterfaceIndices.map((int i) { if (i == noCapabilityIndex) { @@ -402,8 +431,9 @@ abstract class ClassMirrorBase extends _DataCaching implements ClassMirror { // we do have the `typeRelationsCapability`, but we may still // encounter a single unsupported superinterface. throw NoSuchCapabilityError( - 'Requesting a superinterface of `$qualifiedName` ' - 'without capability'); + 'Requesting a superinterface of `$qualifiedName` ' + 'without capability', + ); } return _data.typeMirrors[i] as ClassMirror; }).toList(); @@ -450,23 +480,24 @@ abstract class ClassMirrorBase extends _DataCaching implements ClassMirror { final Map? _parameterListShapes; ClassMirrorBase( - this.simpleName, - this.qualifiedName, - this._descriptor, - this._classIndex, - this._reflector, - this._declarationIndices, - this._instanceMemberIndices, - this._staticMemberIndices, - this._superclassIndex, - this._getters, - this._setters, - this._constructors, - this._ownerIndex, - this._mixinIndex, - this._superinterfaceIndices, - this._metadata, - this._parameterListShapes); + this.simpleName, + this.qualifiedName, + this._descriptor, + this._classIndex, + this._reflector, + this._declarationIndices, + this._instanceMemberIndices, + this._staticMemberIndices, + this._superclassIndex, + this._getters, + this._setters, + this._constructors, + this._ownerIndex, + this._mixinIndex, + this._superinterfaceIndices, + this._metadata, + this._parameterListShapes, + ); @override bool get isAbstract => (_descriptor & constants.abstractAttribute != 0); @@ -487,7 +518,8 @@ abstract class ClassMirrorBase extends _DataCaching implements ClassMirror { // that. if (declarationIndex == noCapabilityIndex) { throw NoSuchCapabilityError( - 'Requesting declarations of "$qualifiedName" without capability'); + 'Requesting declarations of "$qualifiedName" without capability', + ); } DeclarationMirror declarationMirror = _data.memberMirrors![declarationIndex]; @@ -508,7 +540,8 @@ abstract class ClassMirrorBase extends _DataCaching implements ClassMirror { List? instanceMemberIndices = _instanceMemberIndices; if (instanceMemberIndices == null) { throw NoSuchCapabilityError( - 'Requesting instanceMembers without `declarationsCapability`.'); + 'Requesting instanceMembers without `declarationsCapability`.', + ); } var result = {}; for (int instanceMemberIndex in instanceMemberIndices) { @@ -532,7 +565,8 @@ abstract class ClassMirrorBase extends _DataCaching implements ClassMirror { List? staticMemberIndices = _staticMemberIndices; if (staticMemberIndices == null) { throw NoSuchCapabilityError( - 'Requesting instanceMembers without `declarationsCapability`.'); + 'Requesting instanceMembers without `declarationsCapability`.', + ); } var result = {}; for (int staticMemberIndex in staticMemberIndices) { @@ -553,22 +587,28 @@ abstract class ClassMirrorBase extends _DataCaching implements ClassMirror { if (_mixinIndex == noCapabilityIndex) { if (!_supportsTypeRelations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `mixin` for `$qualifiedName` ' - 'without `typeRelationsCapability`'); + 'Attempt to get `mixin` for `$qualifiedName` ' + 'without `typeRelationsCapability`', + ); } throw NoSuchCapabilityError( - 'Attempt to get mixin from "$simpleName" without capability'); + 'Attempt to get mixin from "$simpleName" without capability', + ); } return _data.typeMirrors[_mixinIndex] as ClassMirror; } bool _checkParameterListShape( - String methodName, + String methodName, + int numberOfPositionalArguments, + Iterable? namedArgumentNames, + MethodMirrorProvider methodMirrorProvider, + ) { + bool checkUsingShape( + List parameterListShape, int numberOfPositionalArguments, Iterable? namedArgumentNames, - MethodMirrorProvider methodMirrorProvider) { - bool checkUsingShape(List parameterListShape, - int numberOfPositionalArguments, Iterable? namedArgumentNames) { + ) { assert(parameterListShape.length == 3); int numberOfPositionalParameters = parameterListShape[0]; int numberOfOptionalPositionalParameters = parameterListShape[1]; @@ -586,8 +626,9 @@ abstract class ClassMirrorBase extends _DataCaching implements ClassMirror { // We do have named arguments; check that they are all known. return namesOfNamedParameters == null ? false - : namedArgumentNames - .every((Symbol name) => namesOfNamedParameters.contains(name)); + : namedArgumentNames.every( + (Symbol name) => namesOfNamedParameters.contains(name), + ); } Map? parameterListShapes = _parameterListShapes; @@ -605,8 +646,11 @@ abstract class ClassMirrorBase extends _DataCaching implements ClassMirror { // invocation received an argument list that it supports. It is a bug if // `shapeIndex` is out of range for `parameterListShapes`, but if that // happens the built-in range check will catch it. - return checkUsingShape(_data.parameterListShapes![shapeIndex], - numberOfPositionalArguments, namedArgumentNames); + return checkUsingShape( + _data.parameterListShapes![shapeIndex], + numberOfPositionalArguments, + namedArgumentNames, + ); } else { // Without ready-to-use parameter list shape information we must compute // the shape from declaration mirrors. @@ -627,29 +671,52 @@ abstract class ClassMirrorBase extends _DataCaching implements ClassMirror { var methodMirrorImpl = methodMirror as MethodMirrorImpl; // Let the [methodMirrorImpl] check it based on declaration mirrors. return methodMirrorImpl._isArgumentListShapeAppropriate( - numberOfPositionalArguments, namedArgumentNames); - } - } - - bool _checkInstanceParameterListShape(String methodName, - int numberOfPositionalArguments, Iterable? namedArgumentNames) { - return _checkParameterListShape(methodName, numberOfPositionalArguments, - namedArgumentNames, (String name) => instanceMembers[name]); - } - - bool _checkStaticParameterListShape(String methodName, - int numberOfPositionalArguments, Iterable? namedArgumentNames) { - return _checkParameterListShape(methodName, numberOfPositionalArguments, - namedArgumentNames, (String name) => staticMembers[name]); - } - - @override - Object newInstance(String constructorName, List positionalArguments, - [Map? namedArguments]) { + numberOfPositionalArguments, + namedArgumentNames, + ); + } + } + + bool _checkInstanceParameterListShape( + String methodName, + int numberOfPositionalArguments, + Iterable? namedArgumentNames, + ) { + return _checkParameterListShape( + methodName, + numberOfPositionalArguments, + namedArgumentNames, + (String name) => instanceMembers[name], + ); + } + + bool _checkStaticParameterListShape( + String methodName, + int numberOfPositionalArguments, + Iterable? namedArgumentNames, + ) { + return _checkParameterListShape( + methodName, + numberOfPositionalArguments, + namedArgumentNames, + (String name) => staticMembers[name], + ); + } + + @override + Object newInstance( + String constructorName, + List positionalArguments, [ + Map? namedArguments, + ]) { Never fail() { Type? type = hasReflectedType ? reflectedType : null; throw reflectableNoSuchConstructorError( - type, constructorName, positionalArguments, namedArguments); + type, + constructorName, + positionalArguments, + namedArguments, + ); } Function? constructor = _constructors[constructorName]; @@ -660,28 +727,41 @@ abstract class ClassMirrorBase extends _DataCaching implements ClassMirror { fail(); } return Function.apply( - constructor(true), positionalArguments, namedArguments); + constructor(true), + positionalArguments, + namedArguments, + ); } @override - Object? invoke(String memberName, List positionalArguments, - [Map? namedArguments]) { + Object? invoke( + String memberName, + List positionalArguments, [ + Map? namedArguments, + ]) { Never fail() { throw reflectableNoSuchMethodError( - hasReflectedType ? reflectedType : null, - memberName, - positionalArguments, - namedArguments); + hasReflectedType ? reflectedType : null, + memberName, + positionalArguments, + namedArguments, + ); } StaticGetter? getter = _getters[memberName]; if (getter == null) fail(); if (!_checkStaticParameterListShape( - memberName, positionalArguments.length, namedArguments?.keys)) { + memberName, + positionalArguments.length, + namedArguments?.keys, + )) { fail(); } return Function.apply( - getter() as Function, positionalArguments, namedArguments); + getter() as Function, + positionalArguments, + namedArguments, + ); } @override @@ -699,8 +779,9 @@ abstract class ClassMirrorBase extends _DataCaching implements ClassMirror { _isSetterName(name) ? name : _getterNameToSetterName(name); StaticSetter? setter = _setters[setterName]; if (setter == null) { - throw reflectableNoSuchSetterError( - reflectedType, setterName, [value], {}); + throw reflectableNoSuchSetterError(reflectedType, setterName, [ + value, + ], {}); } return setter(value); } @@ -736,7 +817,8 @@ abstract class ClassMirrorBase extends _DataCaching implements ClassMirror { String description = hasReflectedType ? reflectedType.toString() : qualifiedName; throw NoSuchCapabilityError( - 'Requesting metadata of "$description" without capability'); + 'Requesting metadata of "$description" without capability', + ); } return _metadata; } @@ -762,12 +844,14 @@ abstract class ClassMirrorBase extends _DataCaching implements ClassMirror { // for access to superinterfaces here. if (!_supportsTypeRelations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to evaluate `isAssignableTo` for `$qualifiedName` ' - 'without `typeRelationsCapability`'); + 'Attempt to evaluate `isAssignableTo` for `$qualifiedName` ' + 'without `typeRelationsCapability`', + ); } throw NoSuchCapabilityError( - 'Attempt to evaluate `isAssignableTo` for `$qualifiedName` ' - 'without capability.'); + 'Attempt to evaluate `isAssignableTo` for `$qualifiedName` ' + 'without capability.', + ); } return _isSubtypeOf(other) || (other is ClassMirrorBase && other._isSubtypeOf(this)); @@ -785,12 +869,14 @@ abstract class ClassMirrorBase extends _DataCaching implements ClassMirror { // for access to superinterfaces here. if (!_supportsTypeRelations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to evaluate `isSubtypeOf` for `$qualifiedName` ' - 'without `typeRelationsCapability`'); + 'Attempt to evaluate `isSubtypeOf` for `$qualifiedName` ' + 'without `typeRelationsCapability`', + ); } throw NoSuchCapabilityError( - 'Attempt to evaluate `isSubtypeOf` for `$qualifiedName` ' - 'without capability.'); + 'Attempt to evaluate `isSubtypeOf` for `$qualifiedName` ' + 'without capability.', + ); } return _isSubtypeOf(other); } @@ -808,8 +894,10 @@ abstract class ClassMirrorBase extends _DataCaching implements ClassMirror { // Recursively test hierarchy over `superclass`. if (superclass!._isSubtypeOf(other)) return true; // Recursively test hierarchy over remaining direct supertypes. - return superinterfaces.any((ClassMirror classMirror) => - classMirror is ClassMirrorBase && classMirror._isSubtypeOf(other)); + return superinterfaces.any( + (ClassMirror classMirror) => + classMirror is ClassMirrorBase && classMirror._isSubtypeOf(other), + ); } @override @@ -824,12 +912,14 @@ abstract class ClassMirrorBase extends _DataCaching implements ClassMirror { // for access to superinterfaces here. if (!_supportsTypeRelations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to evaluate `isSubclassOf` for `$qualifiedName` ' - 'without `typeRelationsCapability`'); + 'Attempt to evaluate `isSubclassOf` for `$qualifiedName` ' + 'without `typeRelationsCapability`', + ); } throw NoSuchCapabilityError( - 'Attempt to evaluate `isSubclassOf` for $qualifiedName ' - 'without capability.'); + 'Attempt to evaluate `isSubclassOf` for $qualifiedName ' + 'without capability.', + ); } return _isSubclassOf(other); } @@ -852,12 +942,14 @@ abstract class ClassMirrorBase extends _DataCaching implements ClassMirror { if (_ownerIndex == noCapabilityIndex) { if (!_supportsTypeRelations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `owner` of `$qualifiedName` ' - 'without `typeRelationsCapability`'); + 'Attempt to get `owner` of `$qualifiedName` ' + 'without `typeRelationsCapability`', + ); } throw NoSuchCapabilityError( - 'Trying to get owner of class `$qualifiedName` ' - 'without `libraryCapability`'); + 'Trying to get owner of class `$qualifiedName` ' + 'without `libraryCapability`', + ); } return _data.libraryMirrors![_ownerIndex]; } @@ -867,11 +959,14 @@ abstract class ClassMirrorBase extends _DataCaching implements ClassMirror { if (_superclassIndex == noCapabilityIndex) { if (!_supportsTypeRelations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `superclass` of `$qualifiedName` ' - 'without `typeRelationsCapability`'); + 'Attempt to get `superclass` of `$qualifiedName` ' + 'without `typeRelationsCapability`', + ); } - throw NoSuchCapabilityError('Requesting mirror on un-marked class, ' - '`superclass` of `$qualifiedName`'); + throw NoSuchCapabilityError( + 'Requesting mirror on un-marked class, ' + '`superclass` of `$qualifiedName`', + ); } if (_superclassIndex == null) return null; // Superclass of [Object]. return _data.typeMirrors[_superclassIndex] as ClassMirrorBase?; @@ -880,30 +975,32 @@ abstract class ClassMirrorBase extends _DataCaching implements ClassMirror { class NonGenericClassMirrorImpl extends ClassMirrorBase { NonGenericClassMirrorImpl( - super.simpleName, - super.qualifiedName, - super.descriptor, - super.classIndex, - super.reflector, - super.declarationIndices, - super.instanceMemberIndices, - super.staticMemberIndices, - super.superclassIndex, - super.getters, - super.setters, - super.constructors, - super.ownerIndex, - super.mixinIndex, - super.superinterfaceIndices, - super.metadata, - super.parameterListShapes); + super.simpleName, + super.qualifiedName, + super.descriptor, + super.classIndex, + super.reflector, + super.declarationIndices, + super.instanceMemberIndices, + super.staticMemberIndices, + super.superclassIndex, + super.getters, + super.setters, + super.constructors, + super.ownerIndex, + super.mixinIndex, + super.superinterfaceIndices, + super.metadata, + super.parameterListShapes, + ); @override List get typeArguments { if (!_supportsTypeRelations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `typeArguments` for `$qualifiedName` ' - 'without `typeRelationsCapability`'); + 'Attempt to get `typeArguments` for `$qualifiedName` ' + 'without `typeRelationsCapability`', + ); } return const []; } @@ -913,8 +1010,9 @@ class NonGenericClassMirrorImpl extends ClassMirrorBase { if (!_supportsTypeRelations(_reflector) || !_supportsReflectedType(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `typeArguments` for `$qualifiedName` ' - 'without `typeRelationsCapability` or `reflectedTypeCapability`'); + 'Attempt to get `typeArguments` for `$qualifiedName` ' + 'without `typeRelationsCapability` or `reflectedTypeCapability`', + ); } return const []; } @@ -923,8 +1021,9 @@ class NonGenericClassMirrorImpl extends ClassMirrorBase { List get typeVariables { if (!_supportsTypeRelations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to evaluate `typeVariables` for `$qualifiedName` ' - 'without `typeRelationsCapability`'); + 'Attempt to evaluate `typeVariables` for `$qualifiedName` ' + 'without `typeRelationsCapability`', + ); } return const []; } @@ -936,8 +1035,9 @@ class NonGenericClassMirrorImpl extends ClassMirrorBase { TypeMirror get originalDeclaration { if (!_supportsTypeRelations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `originalDeclaration` for `$qualifiedName` ' - 'without `typeRelationsCapability`'); + 'Attempt to get `originalDeclaration` for `$qualifiedName` ' + 'without `typeRelationsCapability`', + ); } return this; } @@ -982,33 +1082,35 @@ class GenericClassMirrorImpl extends ClassMirrorBase { final int _dynamicReflectedTypeIndex; GenericClassMirrorImpl( - super.simpleName, - super.qualifiedName, - super.descriptor, - super.classIndex, - super.reflector, - super.declarationIndices, - super.instanceMemberIndices, - super.staticMemberIndices, - int super.superclassIndex, - super.getters, - super.setters, - super.constructors, - super.ownerIndex, - super.mixinIndex, - super.superinterfaceIndices, - super.metadata, - super.parameterListShapes, - this._isGenericRuntimeTypeOf, - this._typeVariableIndices, - this._dynamicReflectedTypeIndex); + super.simpleName, + super.qualifiedName, + super.descriptor, + super.classIndex, + super.reflector, + super.declarationIndices, + super.instanceMemberIndices, + super.staticMemberIndices, + int super.superclassIndex, + super.getters, + super.setters, + super.constructors, + super.ownerIndex, + super.mixinIndex, + super.superinterfaceIndices, + super.metadata, + super.parameterListShapes, + this._isGenericRuntimeTypeOf, + this._typeVariableIndices, + this._dynamicReflectedTypeIndex, + ); @override List get typeArguments { if (!_supportsTypeRelations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `typeArguments` for `$qualifiedName` ' - 'without `typeRelationsCapability`'); + 'Attempt to get `typeArguments` for `$qualifiedName` ' + 'without `typeRelationsCapability`', + ); } // This mirror represents the original declaration, so no actual type // arguments have been passed. By convention we represent this situation @@ -1021,8 +1123,9 @@ class GenericClassMirrorImpl extends ClassMirrorBase { if (!_supportsTypeRelations(_reflector) || !_supportsReflectedType(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `reflectedTypeArguments` for `$qualifiedName` ' - 'without `typeRelationsCapability` or `reflectedTypeCapability`'); + 'Attempt to get `reflectedTypeArguments` for `$qualifiedName` ' + 'without `typeRelationsCapability` or `reflectedTypeCapability`', + ); } // This mirror represents the original declaration, so no actual type // arguments have been passed. By convention we represent this situation @@ -1040,11 +1143,13 @@ class GenericClassMirrorImpl extends ClassMirrorBase { if (typeVariableIndices == null) { if (!_supportsTypeRelations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to evaluate `typeVariables` for `$qualifiedName` ' - 'without `typeRelationsCapability`'); + 'Attempt to evaluate `typeVariables` for `$qualifiedName` ' + 'without `typeRelationsCapability`', + ); } throw NoSuchCapabilityError( - 'Requesting type variables of `$qualifiedName` without capability'); + 'Requesting type variables of `$qualifiedName` without capability', + ); } var result = []; for (int typeVariableIndex in typeVariableIndices) { @@ -1062,8 +1167,9 @@ class GenericClassMirrorImpl extends ClassMirrorBase { TypeMirror get originalDeclaration { if (!_supportsTypeRelations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `originalDeclaration` for `$qualifiedName` ' - 'without `typeRelationsCapability`'); + 'Attempt to get `originalDeclaration` for `$qualifiedName` ' + 'without `typeRelationsCapability`', + ); } return this; } @@ -1073,8 +1179,10 @@ class GenericClassMirrorImpl extends ClassMirrorBase { @override Type get reflectedType { - throw UnsupportedError('Attempt to obtain `reflectedType` ' - 'from generic class `$qualifiedName`.'); + throw UnsupportedError( + 'Attempt to obtain `reflectedType` ' + 'from generic class `$qualifiedName`.', + ); } @override @@ -1085,12 +1193,14 @@ class GenericClassMirrorImpl extends ClassMirrorBase { if (_dynamicReflectedTypeIndex == noCapabilityIndex) { if (!_supportsReflectedType(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to evaluate `dynamicReflectedType` for `$qualifiedName` ' - 'without `reflectedTypeCapability`'); + 'Attempt to evaluate `dynamicReflectedType` for `$qualifiedName` ' + 'without `reflectedTypeCapability`', + ); } throw NoSuchCapabilityError( - 'Attempt to get `dynamicReflectedType` for `$qualifiedName` ' - 'without capability'); + 'Attempt to get `dynamicReflectedType` for `$qualifiedName` ' + 'without capability', + ); } return _data.types[_dynamicReflectedTypeIndex]; } @@ -1112,33 +1222,35 @@ class InstantiatedGenericClassMirrorImpl extends ClassMirrorBase { final List? _reflectedTypeArgumentIndices; InstantiatedGenericClassMirrorImpl( - super.simpleName, - super.qualifiedName, - super.descriptor, - super.classIndex, - super.reflector, - super.declarationIndices, - super.instanceMemberIndices, - super.staticMemberIndices, - super.superclassIndex, - super.getters, - super.setters, - super.constructors, - super.ownerIndex, - super.mixinIndex, - super.superinterfaceIndices, - super.metadata, - super.parameterListShapes, - this._originalDeclaration, - this._reflectedType, - this._reflectedTypeArgumentIndices); + super.simpleName, + super.qualifiedName, + super.descriptor, + super.classIndex, + super.reflector, + super.declarationIndices, + super.instanceMemberIndices, + super.staticMemberIndices, + super.superclassIndex, + super.getters, + super.setters, + super.constructors, + super.ownerIndex, + super.mixinIndex, + super.superinterfaceIndices, + super.metadata, + super.parameterListShapes, + this._originalDeclaration, + this._reflectedType, + this._reflectedTypeArgumentIndices, + ); @override List get typeArguments { if (!_supportsTypeRelations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `typeArguments` for `$qualifiedName` ' - 'without `typeRelationsCapability`'); + 'Attempt to get `typeArguments` for `$qualifiedName` ' + 'without `typeRelationsCapability`', + ); } return reflectedTypeArguments .map((Type type) => _reflector.reflectType(type)) @@ -1150,8 +1262,9 @@ class InstantiatedGenericClassMirrorImpl extends ClassMirrorBase { if (!_supportsTypeRelations(_reflector) || !_supportsReflectedType(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `reflectedTypeArguments` for `$qualifiedName` ' - 'without `typeRelationsCapability` or `reflectedTypeCapability`'); + 'Attempt to get `reflectedTypeArguments` for `$qualifiedName` ' + 'without `typeRelationsCapability` or `reflectedTypeCapability`', + ); } List? reflectedTypeArgumentIndices = _reflectedTypeArgumentIndices; if (reflectedTypeArgumentIndices == null) { @@ -1173,8 +1286,9 @@ class InstantiatedGenericClassMirrorImpl extends ClassMirrorBase { TypeMirror get originalDeclaration { if (!_supportsTypeRelations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `originalDeclaration` for `$qualifiedName` ' - 'without `typeRelationsCapability`'); + 'Attempt to get `originalDeclaration` for `$qualifiedName` ' + 'without `typeRelationsCapability`', + ); } return _originalDeclaration; } @@ -1188,8 +1302,10 @@ class InstantiatedGenericClassMirrorImpl extends ClassMirrorBase { if (reflectedType != null) { return reflectedType; } - throw UnsupportedError('Cannot provide `reflectedType` of ' - 'instance of generic type `$simpleName`.'); + throw UnsupportedError( + 'Cannot provide `reflectedType` of ' + 'instance of generic type `$simpleName`.', + ); } @override @@ -1246,34 +1362,36 @@ class InstantiatedGenericClassMirrorImpl extends ClassMirrorBase { } InstantiatedGenericClassMirrorImpl _createInstantiatedGenericClass( - GenericClassMirrorImpl genericClassMirror, - Type? reflectedType, - List? reflectedTypeArguments, - [int? descriptor]) { + GenericClassMirrorImpl genericClassMirror, + Type? reflectedType, + List? reflectedTypeArguments, [ + int? descriptor, +]) { // TODO(eernst) implement: Pass a representation of type arguments to this // method, and create an instantiated generic class which includes that // information. return InstantiatedGenericClassMirrorImpl( - genericClassMirror.simpleName, - genericClassMirror.qualifiedName, - descriptor ?? genericClassMirror._descriptor, - genericClassMirror._classIndex, - genericClassMirror._reflector, - genericClassMirror._declarationIndices, - genericClassMirror._instanceMemberIndices, - genericClassMirror._staticMemberIndices, - genericClassMirror._superclassIndex, - genericClassMirror._getters, - genericClassMirror._setters, - genericClassMirror._constructors, - genericClassMirror._ownerIndex, - genericClassMirror._mixinIndex, - genericClassMirror._superinterfaceIndices, - genericClassMirror._metadata, - genericClassMirror._parameterListShapes, - genericClassMirror, - reflectedType, - reflectedTypeArguments); + genericClassMirror.simpleName, + genericClassMirror.qualifiedName, + descriptor ?? genericClassMirror._descriptor, + genericClassMirror._classIndex, + genericClassMirror._reflector, + genericClassMirror._declarationIndices, + genericClassMirror._instanceMemberIndices, + genericClassMirror._staticMemberIndices, + genericClassMirror._superclassIndex, + genericClassMirror._getters, + genericClassMirror._setters, + genericClassMirror._constructors, + genericClassMirror._ownerIndex, + genericClassMirror._mixinIndex, + genericClassMirror._superinterfaceIndices, + genericClassMirror._metadata, + genericClassMirror._parameterListShapes, + genericClassMirror, + reflectedType, + reflectedTypeArguments, + ); } class TypeVariableMirrorImpl extends _DataCaching @@ -1304,8 +1422,14 @@ class TypeVariableMirrorImpl extends _DataCaching /// means no metadata, null means no capability. final List? _metadata; - TypeVariableMirrorImpl(this.simpleName, this.qualifiedName, this._reflector, - this._upperBoundIndex, this._ownerIndex, this._metadata); + TypeVariableMirrorImpl( + this.simpleName, + this.qualifiedName, + this._reflector, + this._upperBoundIndex, + this._ownerIndex, + this._metadata, + ); @override bool get isStatic => false; @@ -1315,8 +1439,10 @@ class TypeVariableMirrorImpl extends _DataCaching int? upperBoundIndex = _upperBoundIndex; if (upperBoundIndex == null) return DynamicMirrorImpl(); if (upperBoundIndex == noCapabilityIndex) { - throw NoSuchCapabilityError('Attempt to get `upperBound` from type ' - 'variable mirror without capability.'); + throw NoSuchCapabilityError( + 'Attempt to get `upperBound` from type ' + 'variable mirror without capability.', + ); } return _data.typeMirrors[upperBoundIndex]; } @@ -1325,8 +1451,9 @@ class TypeVariableMirrorImpl extends _DataCaching bool isAssignableTo(TypeMirror other) { if (!_supportsTypeRelations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `isAssignableTo` for `$qualifiedName` ' - 'without `typeRelationsCapability`'); + 'Attempt to get `isAssignableTo` for `$qualifiedName` ' + 'without `typeRelationsCapability`', + ); } return upperBound.isSubtypeOf(other) || other.isSubtypeOf(this); } @@ -1335,8 +1462,9 @@ class TypeVariableMirrorImpl extends _DataCaching bool isSubtypeOf(TypeMirror other) { if (!_supportsTypeRelations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `isSubtypeOf` for `$qualifiedName` ' - 'without `typeRelationsCapability`'); + 'Attempt to get `isSubtypeOf` for `$qualifiedName` ' + 'without `typeRelationsCapability`', + ); } return upperBound.isSubtypeOf(other); } @@ -1345,8 +1473,9 @@ class TypeVariableMirrorImpl extends _DataCaching TypeMirror get originalDeclaration { if (!_supportsTypeRelations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `originalDeclaration` for `$qualifiedName` ' - 'without `typeRelationsCapability`'); + 'Attempt to get `originalDeclaration` for `$qualifiedName` ' + 'without `typeRelationsCapability`', + ); } return this; } @@ -1358,8 +1487,9 @@ class TypeVariableMirrorImpl extends _DataCaching List get typeArguments { if (!_supportsTypeRelations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `typeArguments` for `$qualifiedName` ' - 'without `typeRelationsCapability`'); + 'Attempt to get `typeArguments` for `$qualifiedName` ' + 'without `typeRelationsCapability`', + ); } return const []; } @@ -1369,8 +1499,9 @@ class TypeVariableMirrorImpl extends _DataCaching if (!_supportsTypeRelations(_reflector) || !_supportsReflectedType(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `reflectedTypeArguments` for `$qualifiedName` ' - 'without `typeRelationsCapability` or `reflectedTypeCapability`'); + 'Attempt to get `reflectedTypeArguments` for `$qualifiedName` ' + 'without `typeRelationsCapability` or `reflectedTypeCapability`', + ); } return const []; } @@ -1379,16 +1510,19 @@ class TypeVariableMirrorImpl extends _DataCaching List get typeVariables { if (!_supportsTypeRelations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to evaluate `typeVariables` for `$qualifiedName` ' - 'without `typeRelationsCapability`'); + 'Attempt to evaluate `typeVariables` for `$qualifiedName` ' + 'without `typeRelationsCapability`', + ); } return []; } @override Type get reflectedType { - throw UnsupportedError('Attempt to get `reflectedType` from type ' - 'variable $simpleName'); + throw UnsupportedError( + 'Attempt to get `reflectedType` from type ' + 'variable $simpleName', + ); } @override @@ -1397,8 +1531,10 @@ class TypeVariableMirrorImpl extends _DataCaching @override List get metadata { if (_metadata == null) { - throw NoSuchCapabilityError('Attempt to get `metadata` from type ' - 'variable $simpleName without capability'); + throw NoSuchCapabilityError( + 'Attempt to get `metadata` from type ' + 'variable $simpleName without capability', + ); } return []; } @@ -1428,8 +1564,9 @@ class TypeVariableMirrorImpl extends _DataCaching DeclarationMirror get owner { if (_ownerIndex == noCapabilityIndex) { throw NoSuchCapabilityError( - 'Trying to get owner of type parameter `$qualifiedName` ' - 'without capability'); + 'Trying to get owner of type parameter `$qualifiedName` ' + 'without capability', + ); } return _data.typeMirrors[_ownerIndex]; } @@ -1461,14 +1598,15 @@ class LibraryMirrorImpl extends _DataCaching implements LibraryMirror { final Map? _parameterListShapes; LibraryMirrorImpl( - this.simpleName, - this.uri, - this._reflector, - this._declarationIndices, - this.getters, - this.setters, - this._metadata, - this._parameterListShapes); + this.simpleName, + this.uri, + this._reflector, + this._declarationIndices, + this.getters, + this.setters, + this._metadata, + this._parameterListShapes, + ); Map? _declarations; @@ -1486,7 +1624,8 @@ class LibraryMirrorImpl extends _DataCaching implements LibraryMirror { // that. if (declarationIndex == noCapabilityIndex) { throw NoSuchCapabilityError( - 'Requesting declarations of `$qualifiedName` without capability'); + 'Requesting declarations of `$qualifiedName` without capability', + ); } DeclarationMirror declarationMirror = _data.memberMirrors![declarationIndex]; @@ -1503,10 +1642,16 @@ class LibraryMirrorImpl extends _DataCaching implements LibraryMirror { return declarations; } - bool _checkParameterListShape(String memberName, - int numberOfPositionalArguments, Iterable? namedArgumentNames) { - bool checkUsingShape(List parameterListShape, - int numberOfPositionalArguments, Iterable? namedArgumentNames) { + bool _checkParameterListShape( + String memberName, + int numberOfPositionalArguments, + Iterable? namedArgumentNames, + ) { + bool checkUsingShape( + List parameterListShape, + int numberOfPositionalArguments, + Iterable? namedArgumentNames, + ) { assert(parameterListShape.length == 3); int numberOfPositionalParameters = parameterListShape[0]; int numberOfOptionalPositionalParameters = parameterListShape[1]; @@ -1518,8 +1663,9 @@ class LibraryMirrorImpl extends _DataCaching implements LibraryMirror { return false; } if (namedArgumentNames == null) return true; - return namedArgumentNames - .every((Symbol name) => namesOfNamedParameters.contains(name)); + return namedArgumentNames.every( + (Symbol name) => namesOfNamedParameters.contains(name), + ); } Map? parameterListShapes = _parameterListShapes; @@ -1537,8 +1683,11 @@ class LibraryMirrorImpl extends _DataCaching implements LibraryMirror { // invocation received an argument list that it supports. It is a bug if // `shapeIndex` is out of range for `parameterListShapes`, but if that // happens the built-in range check will catch it. - return checkUsingShape(_data.parameterListShapes![shapeIndex], - numberOfPositionalArguments, namedArgumentNames); + return checkUsingShape( + _data.parameterListShapes![shapeIndex], + numberOfPositionalArguments, + namedArgumentNames, + ); } else { // Without ready-to-use parameter list shape information we must compute // the shape from declaration mirrors. @@ -1562,26 +1711,41 @@ class LibraryMirrorImpl extends _DataCaching implements LibraryMirror { var methodMirrorImpl = methodMirror as MethodMirrorImpl; // Let the [methodMirrorImpl] check it based on declaration mirrors. return methodMirrorImpl._isArgumentListShapeAppropriate( - numberOfPositionalArguments, namedArgumentNames); + numberOfPositionalArguments, + namedArgumentNames, + ); } } @override - Object? invoke(String memberName, List positionalArguments, - [Map? namedArguments]) { + Object? invoke( + String memberName, + List positionalArguments, [ + Map? namedArguments, + ]) { Never fail() { throw reflectableNoSuchMethodError( - null, memberName, positionalArguments, namedArguments); + null, + memberName, + positionalArguments, + namedArguments, + ); } StaticGetter? getter = getters[memberName]; if (getter == null) fail(); if (!_checkParameterListShape( - memberName, positionalArguments.length, namedArguments?.keys)) { + memberName, + positionalArguments.length, + namedArguments?.keys, + )) { fail(); } return Function.apply( - getter() as Function, positionalArguments, namedArguments); + getter() as Function, + positionalArguments, + namedArguments, + ); } @override @@ -1621,7 +1785,8 @@ class LibraryMirrorImpl extends _DataCaching implements LibraryMirror { List? metadata = _metadata; if (metadata == null) { throw NoSuchCapabilityError( - 'Requesting metadata of library `$simpleName` without capability'); + 'Requesting metadata of library `$simpleName` without capability', + ); } return metadata; } @@ -1696,16 +1861,17 @@ class MethodMirrorImpl extends _DataCaching implements MethodMirror { final List? _metadata; MethodMirrorImpl( - this._name, - this._descriptor, - this._ownerIndex, - this._returnTypeIndex, - this._reflectedReturnTypeIndex, - this._dynamicReflectedReturnTypeIndex, - this._reflectedTypeArgumentsOfReturnType, - this._parameterIndices, - this._reflector, - this._metadata); + this._name, + this._descriptor, + this._ownerIndex, + this._returnTypeIndex, + this._reflectedReturnTypeIndex, + this._dynamicReflectedReturnTypeIndex, + this._reflectedTypeArgumentsOfReturnType, + this._parameterIndices, + this._reflector, + this._metadata, + ); int get kind => constants.kindFromEncoding(_descriptor); @@ -1713,8 +1879,9 @@ class MethodMirrorImpl extends _DataCaching implements MethodMirror { DeclarationMirror get owner { if (_ownerIndex == noCapabilityIndex) { throw NoSuchCapabilityError( - 'Trying to get owner of method `$qualifiedName` ' - 'without `LibraryCapability`'); + 'Trying to get owner of method `$qualifiedName` ' + 'without `LibraryCapability`', + ); } return isTopLevel ? _data.libraryMirrors![_ownerIndex] @@ -1792,7 +1959,8 @@ class MethodMirrorImpl extends _DataCaching implements MethodMirror { List? metadata = _metadata; if (metadata == null) { throw NoSuchCapabilityError( - 'Requesting metadata of method `$simpleName` without capability'); + 'Requesting metadata of method `$simpleName` without capability', + ); } return metadata; } @@ -1801,7 +1969,8 @@ class MethodMirrorImpl extends _DataCaching implements MethodMirror { List get parameters { if (!_supportsDeclarations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `parameters` without `DeclarationsCapability`'); + 'Attempt to get `parameters` without `DeclarationsCapability`', + ); } return _parameterIndices .map((int parameterIndex) => _data.parameterMirrors![parameterIndex]) @@ -1818,15 +1987,17 @@ class MethodMirrorImpl extends _DataCaching implements MethodMirror { if (_hasNeverReturnType) return VoidMirrorImpl(); if (_returnTypeIndex == noCapabilityIndex) { throw NoSuchCapabilityError( - 'Requesting returnType of method `$simpleName` without capability'); + 'Requesting returnType of method `$simpleName` without capability', + ); } if (_hasClassReturnType) { TypeMirror typeMirror = _data.typeMirrors[_returnTypeIndex]; return _hasGenericReturnType ? _createInstantiatedGenericClass( - typeMirror as GenericClassMirrorImpl, - null, - _reflectedTypeArgumentsOfReturnType) + typeMirror as GenericClassMirrorImpl, + null, + _reflectedTypeArgumentsOfReturnType, + ) : typeMirror; } throw unreachableError('Unexpected kind of returnType'); @@ -1845,8 +2016,10 @@ class MethodMirrorImpl extends _DataCaching implements MethodMirror { if (_hasDynamicReturnType) return dynamic; if (_hasNeverReturnType) return Never; if (_reflectedReturnTypeIndex == noCapabilityIndex) { - throw NoSuchCapabilityError('Requesting reflectedReturnType of method ' - '`$simpleName` without capability'); + throw NoSuchCapabilityError( + 'Requesting reflectedReturnType of method ' + '`$simpleName` without capability', + ); } return _data.types[_reflectedReturnTypeIndex]; } @@ -1864,9 +2037,10 @@ class MethodMirrorImpl extends _DataCaching implements MethodMirror { } @override - String get simpleName => isConstructor - ? (_name == '' ? owner.simpleName : '${owner.simpleName}.$_name') - : _name; + String get simpleName => + isConstructor + ? (_name == '' ? owner.simpleName : '${owner.simpleName}.$_name') + : _name; @override String? get source => null; @@ -1928,7 +2102,9 @@ class MethodMirrorImpl extends _DataCaching implements MethodMirror { Set? _namesOfNamedParameters; bool _isArgumentListShapeAppropriate( - int numberOfPositionalArguments, Iterable? namedArgumentNames) { + int numberOfPositionalArguments, + Iterable? namedArgumentNames, + ) { if (numberOfPositionalArguments < numberOfPositionalParameters - numberOfOptionalPositionalParameters || @@ -1936,8 +2112,9 @@ class MethodMirrorImpl extends _DataCaching implements MethodMirror { return false; } if (namedArgumentNames == null) return true; - return namedArgumentNames - .every((Symbol name) => namesOfNamedParameters.contains(name)); + return namedArgumentNames.every( + (Symbol name) => namesOfNamedParameters.contains(name), + ); } @override @@ -1958,7 +2135,10 @@ abstract class ImplicitAccessorMirrorImpl extends _DataCaching _data.memberMirrors![_variableMirrorIndex] as VariableMirrorImpl; ImplicitAccessorMirrorImpl( - this._reflector, this._variableMirrorIndex, this._selfIndex); + this._reflector, + this._variableMirrorIndex, + this._selfIndex, + ); int get kind => constants.kindFromEncoding(_variableMirror._descriptor); @@ -2032,7 +2212,10 @@ abstract class ImplicitAccessorMirrorImpl extends _DataCaching class ImplicitGetterMirrorImpl extends ImplicitAccessorMirrorImpl { ImplicitGetterMirrorImpl( - super.reflector, super.variableMirrorIndex, super.selfIndex); + super.reflector, + super.variableMirrorIndex, + super.selfIndex, + ); @override bool get isGetter => true; @@ -2044,7 +2227,8 @@ class ImplicitGetterMirrorImpl extends ImplicitAccessorMirrorImpl { List get parameters { if (!_supportsDeclarations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `parameters` without `DeclarationsCapability`'); + 'Attempt to get `parameters` without `DeclarationsCapability`', + ); } return []; } @@ -2061,7 +2245,10 @@ class ImplicitGetterMirrorImpl extends ImplicitAccessorMirrorImpl { class ImplicitSetterMirrorImpl extends ImplicitAccessorMirrorImpl { ImplicitSetterMirrorImpl( - super.reflector, super.variableMirrorIndex, super.selfIndex); + super.reflector, + super.variableMirrorIndex, + super.selfIndex, + ); @override bool get isGetter => false; @@ -2087,21 +2274,23 @@ class ImplicitSetterMirrorImpl extends ImplicitAccessorMirrorImpl { List get parameters { if (!_supportsDeclarations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `parameters` without `DeclarationsCapability`'); + 'Attempt to get `parameters` without `DeclarationsCapability`', + ); } return [ ParameterMirrorImpl( - _variableMirror.simpleName, - _parameterDescriptor, - _selfIndex, - _variableMirror._reflector, - _variableMirror._classMirrorIndex, - _variableMirror._reflectedTypeIndex, - _variableMirror._dynamicReflectedTypeIndex, - _variableMirror._reflectedTypeArguments, - const [], - null, - null) + _variableMirror.simpleName, + _parameterDescriptor, + _selfIndex, + _variableMirror._reflector, + _variableMirror._classMirrorIndex, + _variableMirror._reflectedTypeIndex, + _variableMirror._dynamicReflectedTypeIndex, + _variableMirror._reflectedTypeArguments, + const [], + null, + null, + ), ]; } @@ -2131,15 +2320,16 @@ abstract class VariableMirrorBase extends _DataCaching final List? _metadata; VariableMirrorBase( - this._name, - this._descriptor, - this._ownerIndex, - this._reflector, - this._classMirrorIndex, - this._reflectedTypeIndex, - this._dynamicReflectedTypeIndex, - this._reflectedTypeArguments, - this._metadata); + this._name, + this._descriptor, + this._ownerIndex, + this._reflector, + this._classMirrorIndex, + this._reflectedTypeIndex, + this._dynamicReflectedTypeIndex, + this._reflectedTypeArguments, + this._metadata, + ); int get kind => constants.kindFromEncoding(_descriptor); @@ -2176,7 +2366,8 @@ abstract class VariableMirrorBase extends _DataCaching List? metadata = _metadata; if (metadata == null) { throw NoSuchCapabilityError( - 'Requesting metadata of field `$simpleName` without capability'); + 'Requesting metadata of field `$simpleName` without capability', + ); } return metadata; } @@ -2195,10 +2386,12 @@ abstract class VariableMirrorBase extends _DataCaching if (_classMirrorIndex == noCapabilityIndex) { if (!_supportsType(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `type` without `TypeCapability`'); + 'Attempt to get `type` without `TypeCapability`', + ); } throw NoSuchCapabilityError( - 'Attempt to get class mirror for un-marked class (type of `$_name`)'); + 'Attempt to get class mirror for un-marked class (type of `$_name`)', + ); } if (_isClassType) { TypeMirror typeMirror = _data.typeMirrors[_classMirrorIndex]; @@ -2206,10 +2399,11 @@ abstract class VariableMirrorBase extends _DataCaching typeMirror.isNonNullable != _isNonNullable) { if (_isGenericType) { return _createInstantiatedGenericClass( - typeMirror as GenericClassMirrorImpl, - hasReflectedType ? reflectedType : null, - _reflectedTypeArguments, - _descriptor); + typeMirror as GenericClassMirrorImpl, + hasReflectedType ? reflectedType : null, + _reflectedTypeArguments, + _descriptor, + ); } else { var classMirror = typeMirror as NonGenericClassMirrorImpl; return NonGenericClassMirrorImpl( @@ -2235,9 +2429,10 @@ abstract class VariableMirrorBase extends _DataCaching } else { return _isGenericType ? _createInstantiatedGenericClass( - typeMirror as GenericClassMirrorImpl, - hasReflectedType ? reflectedType : null, - _reflectedTypeArguments) + typeMirror as GenericClassMirrorImpl, + hasReflectedType ? reflectedType : null, + _reflectedTypeArguments, + ) : typeMirror; } } @@ -2259,10 +2454,12 @@ abstract class VariableMirrorBase extends _DataCaching if (_reflectedTypeIndex == noCapabilityIndex) { if (!_supportsReflectedType(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `reflectedType` without `reflectedTypeCapability`'); + 'Attempt to get `reflectedType` without `reflectedTypeCapability`', + ); } throw UnsupportedError( - 'Attempt to get reflectedType without capability (of `$_name`)'); + 'Attempt to get reflectedType without capability (of `$_name`)', + ); } return _data.types[_reflectedTypeIndex]; } @@ -2292,8 +2489,9 @@ class VariableMirrorImpl extends VariableMirrorBase { DeclarationMirror get owner { if (_ownerIndex == noCapabilityIndex) { throw NoSuchCapabilityError( - 'Trying to get owner of variable `$qualifiedName` ' - 'without capability'); + 'Trying to get owner of variable `$qualifiedName` ' + 'without capability', + ); } return isTopLevel ? _data.libraryMirrors![_ownerIndex] @@ -2307,15 +2505,16 @@ class VariableMirrorImpl extends VariableMirrorBase { bool get isConst => (_descriptor & constants.constAttribute != 0); VariableMirrorImpl( - super.name, - super.descriptor, - super.ownerIndex, - super.reflectable, - super.classMirrorIndex, - super.reflectedTypeIndex, - super.dynamicReflectedTypeIndex, - super.reflectedTypeArguments, - super.metadata); + super.name, + super.descriptor, + super.ownerIndex, + super.reflectable, + super.classMirrorIndex, + super.reflectedTypeIndex, + super.dynamicReflectedTypeIndex, + super.reflectedTypeArguments, + super.metadata, + ); // Note that the corresponding implementation of [hashCode] is inherited from // [VariableMirrorBase]. @@ -2347,7 +2546,8 @@ class ParameterMirrorImpl extends VariableMirrorBase bool get hasDefaultValue { if (!_supportsDeclarations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `hasDefaultValue` without `DeclarationsCapability`'); + 'Attempt to get `hasDefaultValue` without `DeclarationsCapability`', + ); } return (_descriptor & constants.hasDefaultValueAttribute != 0); } @@ -2356,7 +2556,8 @@ class ParameterMirrorImpl extends VariableMirrorBase Object? get defaultValue { if (!_supportsDeclarations(_reflector)) { throw NoSuchCapabilityError( - 'Attempt to get `defaultValue` without `DeclarationsCapability`'); + 'Attempt to get `defaultValue` without `DeclarationsCapability`', + ); } return _defaultValue; } @@ -2371,17 +2572,18 @@ class ParameterMirrorImpl extends VariableMirrorBase MethodMirror get owner => _data.memberMirrors![_ownerIndex] as MethodMirror; ParameterMirrorImpl( - super.name, - super.descriptor, - super.ownerIndex, - super.reflectable, - super.classMirrorIndex, - super.reflectedTypeIndex, - super.dynamicReflectedTypeIndex, - super.reflectedTypeArguments, - super.metadata, - this._defaultValue, - this._nameSymbol); + super.name, + super.descriptor, + super.ownerIndex, + super.reflectable, + super.classMirrorIndex, + super.reflectedTypeIndex, + super.dynamicReflectedTypeIndex, + super.reflectedTypeArguments, + super.metadata, + this._defaultValue, + this._nameSymbol, + ); // Note that the corresponding implementation of [hashCode] is inherited from // [VariableMirrorBase]. @@ -2534,20 +2736,21 @@ abstract class ReflectableImpl extends ReflectableBase implements ReflectableInterface { /// Const constructor, to enable usage as metadata, allowing for varargs /// style invocation with up to ten arguments. - const ReflectableImpl( - [super.cap0, - super.cap1, - super.cap2, - super.cap3, - super.cap4, - super.cap5, - super.cap6, - super.cap7, - super.cap8, - super.cap9]); + const ReflectableImpl([ + super.cap0, + super.cap1, + super.cap2, + super.cap3, + super.cap4, + super.cap5, + super.cap6, + super.cap7, + super.cap8, + super.cap9, + ]); const ReflectableImpl.fromList(List super.capabilities) - : super.fromList(); + : super.fromList(); @override bool canReflect(Object reflectee) { @@ -2560,8 +2763,9 @@ abstract class ReflectableImpl extends ReflectableBase } bool get _hasTypeCapability { - return capabilities - .any((ReflectCapability capability) => capability is TypeCapability); + return capabilities.any( + (ReflectCapability capability) => capability is TypeCapability, + ); } @override @@ -2574,7 +2778,8 @@ abstract class ReflectableImpl extends ReflectableBase TypeMirror? result = data[this]!.typeMirrorForType(type); if (result == null || !_hasTypeCapability) { throw NoSuchCapabilityError( - 'Reflecting on type `$type` without capability'); + 'Reflecting on type `$type` without capability', + ); } return result; } @@ -2583,8 +2788,10 @@ abstract class ReflectableImpl extends ReflectableBase LibraryMirror findLibrary(String libraryName) { ReflectorData reflectorData = data[this]!; if (reflectorData.libraryMirrors == null) { - throw NoSuchCapabilityError('Using `findLibrary` without capability. ' - 'Try adding `libraryCapability`.'); + throw NoSuchCapabilityError( + 'Using `findLibrary` without capability. ' + 'Try adding `libraryCapability`.', + ); } // The specification says that an exception shall be thrown if there // is anything other than one library with a matching name. @@ -2610,8 +2817,10 @@ abstract class ReflectableImpl extends ReflectableBase Map get libraries { ReflectorData reflectorData = data[this]!; if (reflectorData.libraryMirrors == null) { - throw NoSuchCapabilityError('Using `libraries` without capability. ' - 'Try adding `libraryCapability`.'); + throw NoSuchCapabilityError( + 'Using `libraries` without capability. ' + 'Try adding `libraryCapability`.', + ); } var result = {}; for (LibraryMirror library in reflectorData.libraryMirrors!) { @@ -2623,7 +2832,8 @@ abstract class ReflectableImpl extends ReflectableBase @override Iterable get annotatedClasses { return List.unmodifiable( - data[this]!.typeMirrors.whereType()); + data[this]!.typeMirrors.whereType(), + ); } } @@ -2643,21 +2853,25 @@ bool _isSetterName(String name) => name.endsWith('='); String _getterNameToSetterName(String name) => '$name='; bool _supportsType(ReflectableImpl reflector) { - return reflector.capabilities - .any((ReflectCapability capability) => capability is TypeCapability); + return reflector.capabilities.any( + (ReflectCapability capability) => capability is TypeCapability, + ); } bool _supportsTypeRelations(ReflectableImpl reflector) { return reflector.capabilities.any( - (ReflectCapability capability) => capability is TypeRelationsCapability); + (ReflectCapability capability) => capability is TypeRelationsCapability, + ); } bool _supportsReflectedType(ReflectableImpl reflector) { return reflector.capabilities.any( - (ReflectCapability capability) => capability == reflectedTypeCapability); + (ReflectCapability capability) => capability == reflectedTypeCapability, + ); } bool _supportsDeclarations(ReflectableImpl reflector) { return reflector.capabilities.any( - (ReflectCapability capability) => capability is DeclarationsCapability); + (ReflectCapability capability) => capability is DeclarationsCapability, + ); } diff --git a/reflectable/pubspec.yaml b/reflectable/pubspec.yaml index 5629718..2aef080 100644 --- a/reflectable/pubspec.yaml +++ b/reflectable/pubspec.yaml @@ -1,23 +1,23 @@ name: reflectable -version: 4.0.12 +version: 4.0.13 description: > Reflection support based on code generation, using 'capabilities' to specify which operations to support, on which objects. homepage: https://github.com/google/reflectable.dart environment: - sdk: '>=3.5.0 <4.0.0' + sdk: '>=3.7.0 <4.0.0' dependencies: - analyzer: ^6.8.0 + analyzer: ">=7.3.0 <7.4.0" build: ^2.4.0 - build_resolvers: ^2.4.0 build_config: ^1.1.0 - build_runner: ^2.4.0 - build_runner_core: ^7.2.0 - dart_style: ^2.3.0 + build_runner: ^2.4.15 + build_runner_core: ^8.0.0 + dart_style: ^3.0.0 glob: ^2.1.0 logging: ^1.2.0 package_config: ^2.1.0 path: ^1.9.0 + pub_semver: ^2.2.0 source_span: ^1.10.0 dev_dependencies: build_test: ^2.2.0 diff --git a/test_reflectable/analysis_options.yaml b/test_reflectable/analysis_options.yaml index 0d00267..63cb56c 100644 --- a/test_reflectable/analysis_options.yaml +++ b/test_reflectable/analysis_options.yaml @@ -1,4 +1,5 @@ include: package:lints/recommended.yaml linter: rules: - - await_only_futures + await_only_futures: true + unnecessary_library_name: false diff --git a/test_reflectable/pubspec.yaml b/test_reflectable/pubspec.yaml index 48b11a7..bad0055 100644 --- a/test_reflectable/pubspec.yaml +++ b/test_reflectable/pubspec.yaml @@ -7,7 +7,7 @@ description: > package. It is not intended to be useful for other purposes than testing package reflectable. environment: - sdk: '>=3.4.0 <4.0.0' + sdk: '>=3.7.0 <4.0.0' dependencies: build_runner: any glob: any