refactor: refactoring reflection system pass 43 fail 1

This commit is contained in:
Patrick Stewart 2024-12-21 09:53:25 -07:00
parent 8bab6aa4b8
commit 14e1fc099d
63 changed files with 1621 additions and 666 deletions

View file

@ -1,4 +1,4 @@
import 'package:platform_reflection/reflection.dart'; import 'package:platform_reflection/mirrors.dart';
// Custom annotation to demonstrate metadata // Custom annotation to demonstrate metadata
class Validate { class Validate {

View file

@ -0,0 +1,60 @@
library mirrors;
import 'package:platform_contracts/contracts.dart';
import 'src/mirrors/mirror_system.dart';
import 'src/mirrors/instance_mirror.dart';
/// Core
export 'src/core/library_scanner.dart';
export 'src/core/reflector.dart';
export 'src/core/runtime_reflector.dart';
export 'src/core/scanner.dart';
/// MirrorSystem
export 'src/mirrors/mirror_system.dart';
/// Mirrors
export 'src/mirrors/base_mirror.dart';
export 'src/mirrors/class_mirror.dart';
export 'src/mirrors/combinator_mirror.dart';
export 'src/mirrors/instance_mirror.dart';
export 'src/mirrors/isolate_mirror.dart';
export 'src/mirrors/library_dependency_mirror.dart';
export 'src/mirrors/library_mirror.dart';
export 'src/mirrors/method_mirror.dart';
export 'src/mirrors/parameter_mirror.dart';
export 'src/mirrors/type_mirror.dart';
export 'src/mirrors/type_variable_mirror.dart';
export 'src/mirrors/variable_mirror.dart';
/// Types
export 'src/mirrors/special_types.dart';
/// Metadata and Annotations
export 'src/annotations.dart';
export 'src/metadata.dart';
/// Exceptions
export 'src/exceptions.dart';
/// Reflects an instance.
InstanceMirrorContract reflect(dynamic reflectee) {
return InstanceMirror(
reflectee: reflectee,
type: reflectClass(reflectee.runtimeType),
);
}
/// Reflects a class.
ClassMirrorContract reflectClass(Type key) {
return MirrorSystem.instance.reflectClass(key);
}
/// Reflects a type.
TypeMirrorContract reflectType(Type key) {
return MirrorSystem.instance.reflectType(key);
}
/// Returns the current mirror system.
MirrorSystemContract currentMirrorSystem() => MirrorSystem.current();

View file

@ -1,18 +0,0 @@
/// A lightweight, cross-platform reflection system for Dart.
library reflection;
// Core functionality
export 'src/core/reflector.dart';
export 'src/core/scanner.dart';
export 'src/core/runtime_reflector.dart';
// Mirror API
export 'src/mirrors.dart';
export 'src/mirrors/isolate_mirror_impl.dart' show IsolateMirrorImpl;
// Metadata and annotations
export 'src/metadata.dart';
export 'src/annotations.dart' show reflectable;
// Exceptions
export 'src/exceptions.dart';

View file

@ -1,4 +1,4 @@
import 'metadata.dart'; import 'package:platform_reflection/mirrors.dart';
/// Registry of reflectable types and their metadata. /// Registry of reflectable types and their metadata.
class ReflectionRegistry { class ReflectionRegistry {

View file

@ -1,9 +1,6 @@
import 'dart:core'; import 'dart:core';
import '../metadata.dart'; import 'package:platform_contracts/contracts.dart';
import '../mirrors.dart'; import 'package:platform_reflection/mirrors.dart';
import '../mirrors/mirror_system_impl.dart';
import '../mirrors/special_types.dart';
import '../exceptions.dart';
/// Runtime scanner that analyzes libraries and extracts their metadata. /// Runtime scanner that analyzes libraries and extracts their metadata.
class LibraryScanner { class LibraryScanner {
@ -89,7 +86,7 @@ class LibraryAnalyzer {
), ),
], ],
returnsVoid: false, returnsVoid: false,
returnType: InstanceMirror, returnType: InstanceMirrorContract,
isPrivate: false, isPrivate: false,
), ),
FunctionInfo( FunctionInfo(
@ -104,7 +101,7 @@ class LibraryAnalyzer {
), ),
], ],
returnsVoid: false, returnsVoid: false,
returnType: ClassMirror, returnType: ClassMirrorContract,
isPrivate: false, isPrivate: false,
), ),
]); ]);
@ -112,7 +109,7 @@ class LibraryAnalyzer {
variables.addAll([ variables.addAll([
VariableInfo( VariableInfo(
name: 'currentMirrorSystem', name: 'currentMirrorSystem',
type: MirrorSystem, type: MirrorSystemContract,
isFinal: true, isFinal: true,
isConst: false, isConst: false,
isPrivate: false, isPrivate: false,

View file

@ -1,8 +1,5 @@
import 'dart:collection'; import 'dart:collection';
import '../metadata.dart'; import 'package:platform_reflection/mirrors.dart';
import '../mirrors.dart';
import '../mirrors/mirrors.dart';
import '../mirrors/special_types.dart';
/// Static registry for reflection metadata. /// Static registry for reflection metadata.
class Reflector { class Reflector {

View file

@ -1,22 +1,6 @@
import 'package:meta/meta.dart';
import 'dart:isolate' as isolate; import 'dart:isolate' as isolate;
import '../exceptions.dart'; import 'package:platform_contracts/contracts.dart';
import '../metadata.dart'; import 'package:platform_reflection/mirrors.dart';
import '../mirrors.dart';
import 'reflector.dart';
import '../mirrors/base_mirror.dart';
import '../mirrors/class_mirror_impl.dart';
import '../mirrors/instance_mirror_impl.dart';
import '../mirrors/method_mirror_impl.dart';
import '../mirrors/parameter_mirror_impl.dart';
import '../mirrors/type_mirror_impl.dart';
import '../mirrors/type_variable_mirror_impl.dart';
import '../mirrors/variable_mirror_impl.dart';
import '../mirrors/library_mirror_impl.dart';
import '../mirrors/library_dependency_mirror_impl.dart';
import '../mirrors/isolate_mirror_impl.dart';
import '../mirrors/mirror_system_impl.dart';
import '../mirrors/special_types.dart';
/// A pure runtime reflection system that provides type introspection and manipulation. /// A pure runtime reflection system that provides type introspection and manipulation.
class RuntimeReflector { class RuntimeReflector {
@ -24,26 +8,26 @@ class RuntimeReflector {
static final instance = RuntimeReflector._(); static final instance = RuntimeReflector._();
/// The current mirror system. /// The current mirror system.
late final MirrorSystemImpl _mirrorSystem; late final MirrorSystem _mirrorSystem;
/// Cache of class mirrors to prevent infinite recursion /// Cache of class mirrors to prevent infinite recursion
final Map<Type, ClassMirror> _classMirrorCache = {}; final Map<Type, ClassMirrorContract> _classMirrorCache = {};
RuntimeReflector._() { RuntimeReflector._() {
// Initialize mirror system // Initialize mirror system
_mirrorSystem = MirrorSystemImpl.current(); _mirrorSystem = MirrorSystem.current();
} }
/// Resolves parameters for method or constructor invocation /// Resolves parameters for method or constructor invocation
List<dynamic> resolveParameters( List<dynamic> resolveParameters(
List<ParameterMirror> parameters, List<ParameterMirrorContract> parameters,
List<dynamic> positionalArgs, List<dynamic> positionalArgs,
Map<Symbol, dynamic>? namedArgs, Map<Symbol, dynamic>? namedArgs,
) { ) {
final resolvedArgs = List<dynamic>.filled(parameters.length, null); final resolvedArgs = List<dynamic>.filled(parameters.length, null);
var positionalIndex = 0; var positionalIndex = 0;
ClassMirror? _getClassMirror(Type? type) { ClassMirrorContract? _getClassMirror(Type? type) {
if (type == null) return null; if (type == null) return null;
try { try {
return reflectClass(type); return reflectClass(type);
@ -52,7 +36,7 @@ class RuntimeReflector {
} }
} }
bool _isTypeCompatible(dynamic value, TypeMirror expectedType) { bool _isTypeCompatible(dynamic value, TypeMirrorContract expectedType) {
// Handle null values // Handle null values
if (value == null) { if (value == null) {
// For now, accept null for any type as we don't have nullability information // For now, accept null for any type as we don't have nullability information
@ -81,7 +65,7 @@ class RuntimeReflector {
} }
// Handle generic type parameters // Handle generic type parameters
if (expectedType is TypeVariableMirrorImpl) { if (expectedType is TypeVariableMirror) {
return _isTypeCompatible(value, expectedType.upperBound); return _isTypeCompatible(value, expectedType.upperBound);
} }
@ -198,9 +182,9 @@ class RuntimeReflector {
// Resolve parameters using constructor metadata // Resolve parameters using constructor metadata
final resolvedArgs = resolveParameters( final resolvedArgs = resolveParameters(
constructor.parameters constructor.parameters
.map((param) => ParameterMirrorImpl( .map((param) => ParameterMirror(
name: param.name, name: param.name,
type: TypeMirrorImpl( type: TypeMirror(
type: param.type, type: param.type,
name: param.type.toString(), name: param.type.toString(),
owner: mirror, owner: mirror,
@ -242,14 +226,15 @@ class RuntimeReflector {
} }
/// Creates a TypeMirror for a given type. /// Creates a TypeMirror for a given type.
TypeMirror _createTypeMirror(Type type, String name, [ClassMirror? owner]) { TypeMirrorContract _createTypeMirror(Type type, String name,
[ClassMirrorContract? owner]) {
if (type == voidType) { if (type == voidType) {
return TypeMirrorImpl.voidType(owner); return TypeMirror.voidType(owner);
} }
if (type == dynamicType) { if (type == dynamicType) {
return TypeMirrorImpl.dynamicType(owner); return TypeMirror.dynamicType(owner);
} }
return TypeMirrorImpl( return TypeMirror(
type: type, type: type,
name: name, name: name,
owner: owner, owner: owner,
@ -258,7 +243,7 @@ class RuntimeReflector {
} }
/// Reflects on a type, returning its class mirror. /// Reflects on a type, returning its class mirror.
ClassMirror reflectClass(Type type) { ClassMirrorContract reflectClass(Type type) {
// Check cache first // Check cache first
if (_classMirrorCache.containsKey(type)) { if (_classMirrorCache.containsKey(type)) {
return _classMirrorCache[type]!; return _classMirrorCache[type]!;
@ -270,7 +255,7 @@ class RuntimeReflector {
} }
// Create empty mirror and add to cache to break recursion // Create empty mirror and add to cache to break recursion
final emptyMirror = ClassMirrorImpl( final emptyMirror = ClassMirror(
type: type, type: type,
name: type.toString(), name: type.toString(),
owner: null, owner: null,
@ -288,11 +273,11 @@ class RuntimeReflector {
final typeMetadata = Reflector.getTypeMetadata(type); final typeMetadata = Reflector.getTypeMetadata(type);
// Create declarations map // Create declarations map
final declarations = <Symbol, DeclarationMirror>{}; final declarations = <Symbol, DeclarationMirrorContract>{};
// Add properties as variable declarations // Add properties as variable declarations
properties.forEach((name, prop) { properties.forEach((name, prop) {
declarations[Symbol(name)] = VariableMirrorImpl( declarations[Symbol(name)] = VariableMirror(
name: name, name: name,
type: _createTypeMirror(prop.type, prop.type.toString(), emptyMirror), type: _createTypeMirror(prop.type, prop.type.toString(), emptyMirror),
owner: emptyMirror, owner: emptyMirror,
@ -305,15 +290,15 @@ class RuntimeReflector {
// Add methods as method declarations // Add methods as method declarations
methods.forEach((name, method) { methods.forEach((name, method) {
declarations[Symbol(name)] = MethodMirrorImpl( declarations[Symbol(name)] = MethodMirror(
name: name, name: name,
owner: emptyMirror, owner: emptyMirror,
returnType: method.returnsVoid returnType: method.returnsVoid
? TypeMirrorImpl.voidType(emptyMirror) ? TypeMirror.voidType(emptyMirror)
: _createTypeMirror( : _createTypeMirror(
method.returnType, method.returnType.toString(), emptyMirror), method.returnType, method.returnType.toString(), emptyMirror),
parameters: method.parameters parameters: method.parameters
.map((param) => ParameterMirrorImpl( .map((param) => ParameterMirror(
name: param.name, name: param.name,
type: _createTypeMirror( type: _createTypeMirror(
param.type, param.type.toString(), emptyMirror), param.type, param.type.toString(), emptyMirror),
@ -334,12 +319,12 @@ class RuntimeReflector {
// Add constructors as method declarations // Add constructors as method declarations
for (final ctor in constructors) { for (final ctor in constructors) {
declarations[Symbol(ctor.name)] = MethodMirrorImpl( declarations[Symbol(ctor.name)] = MethodMirror(
name: ctor.name, name: ctor.name,
owner: emptyMirror, owner: emptyMirror,
returnType: emptyMirror, returnType: emptyMirror,
parameters: ctor.parameters parameters: ctor.parameters
.map((param) => ParameterMirrorImpl( .map((param) => ParameterMirror(
name: param.name, name: param.name,
type: _createTypeMirror( type: _createTypeMirror(
param.type, param.type.toString(), emptyMirror), param.type, param.type.toString(), emptyMirror),
@ -360,11 +345,11 @@ class RuntimeReflector {
} }
// Create instance and static member maps // Create instance and static member maps
final instanceMembers = <Symbol, MethodMirror>{}; final instanceMembers = <Symbol, MethodMirrorContract>{};
final staticMembers = <Symbol, MethodMirror>{}; final staticMembers = <Symbol, MethodMirrorContract>{};
methods.forEach((name, method) { methods.forEach((name, method) {
final methodMirror = declarations[Symbol(name)] as MethodMirror; final methodMirror = declarations[Symbol(name)] as MethodMirrorContract;
if (method.isStatic) { if (method.isStatic) {
staticMembers[Symbol(name)] = methodMirror; staticMembers[Symbol(name)] = methodMirror;
} else { } else {
@ -373,7 +358,7 @@ class RuntimeReflector {
}); });
// Create class mirror // Create class mirror
final mirror = ClassMirrorImpl( final mirror = ClassMirror(
type: type, type: type,
name: type.toString(), name: type.toString(),
owner: null, owner: null,
@ -403,7 +388,7 @@ class RuntimeReflector {
} }
/// Reflects on a type, returning its type mirror. /// Reflects on a type, returning its type mirror.
TypeMirror reflectType(Type type) { TypeMirrorContract reflectType(Type type) {
// Check if type is reflectable // Check if type is reflectable
if (!Reflector.isReflectable(type)) { if (!Reflector.isReflectable(type)) {
throw NotReflectableException(type); throw NotReflectableException(type);
@ -413,22 +398,22 @@ class RuntimeReflector {
} }
/// Creates a new instance reflector for the given object. /// Creates a new instance reflector for the given object.
InstanceMirror reflect(Object instance) { InstanceMirrorContract reflect(Object instance) {
// Check if type is reflectable // Check if type is reflectable
if (!Reflector.isReflectable(instance.runtimeType)) { if (!Reflector.isReflectable(instance.runtimeType)) {
throw NotReflectableException(instance.runtimeType); throw NotReflectableException(instance.runtimeType);
} }
return InstanceMirrorImpl( return InstanceMirror(
reflectee: instance, reflectee: instance,
type: reflectClass(instance.runtimeType), type: reflectClass(instance.runtimeType),
); );
} }
/// Reflects on a library, returning its library mirror. /// Reflects on a library, returning its library mirror.
LibraryMirror reflectLibrary(Uri uri) { LibraryMirrorContract reflectLibrary(Uri uri) {
// Create library mirror with declarations // Create library mirror with declarations
final library = LibraryMirrorImpl.withDeclarations( final library = LibraryMirror.withDeclarations(
name: uri.toString(), name: uri.toString(),
uri: uri, uri: uri,
owner: null, owner: null,
@ -443,30 +428,30 @@ class RuntimeReflector {
} }
/// Gets library dependencies for a given URI. /// Gets library dependencies for a given URI.
List<LibraryDependencyMirror> _getLibraryDependencies(Uri uri) { List<LibraryDependencyMirrorContract> _getLibraryDependencies(Uri uri) {
// Create source library // Create source library
final sourceLibrary = LibraryMirrorImpl.withDeclarations( final sourceLibrary = LibraryMirror.withDeclarations(
name: uri.toString(), name: uri.toString(),
uri: uri, uri: uri,
owner: null, owner: null,
); );
// Create core library as target // Create core library as target
final coreLibrary = LibraryMirrorImpl.withDeclarations( final coreLibrary = LibraryMirror.withDeclarations(
name: 'dart:core', name: 'dart:core',
uri: Uri.parse('dart:core'), uri: Uri.parse('dart:core'),
owner: null, owner: null,
); );
// Create test library as target // Create test library as target
final testLibrary = LibraryMirrorImpl.withDeclarations( final testLibrary = LibraryMirror.withDeclarations(
name: 'package:test/test.dart', name: 'package:test/test.dart',
uri: Uri.parse('package:test/test.dart'), uri: Uri.parse('package:test/test.dart'),
owner: null, owner: null,
); );
// Create reflection library as target // Create reflection library as target
final reflectionLibrary = LibraryMirrorImpl.withDeclarations( final reflectionLibrary = LibraryMirror.withDeclarations(
name: 'package:platform_reflection/reflection.dart', name: 'package:platform_reflection/reflection.dart',
uri: Uri.parse('package:platform_reflection/reflection.dart'), uri: Uri.parse('package:platform_reflection/reflection.dart'),
owner: null, owner: null,
@ -474,7 +459,7 @@ class RuntimeReflector {
return [ return [
// Import dependencies // Import dependencies
LibraryDependencyMirrorImpl( LibraryDependencyMirror(
isImport: true, isImport: true,
isDeferred: false, isDeferred: false,
sourceLibrary: sourceLibrary, sourceLibrary: sourceLibrary,
@ -482,7 +467,7 @@ class RuntimeReflector {
prefix: null, prefix: null,
combinators: const [], combinators: const [],
), ),
LibraryDependencyMirrorImpl( LibraryDependencyMirror(
isImport: true, isImport: true,
isDeferred: false, isDeferred: false,
sourceLibrary: sourceLibrary, sourceLibrary: sourceLibrary,
@ -490,7 +475,7 @@ class RuntimeReflector {
prefix: null, prefix: null,
combinators: const [], combinators: const [],
), ),
LibraryDependencyMirrorImpl( LibraryDependencyMirror(
isImport: true, isImport: true,
isDeferred: false, isDeferred: false,
sourceLibrary: sourceLibrary, sourceLibrary: sourceLibrary,
@ -499,7 +484,7 @@ class RuntimeReflector {
combinators: const [], combinators: const [],
), ),
// Export dependencies // Export dependencies
LibraryDependencyMirrorImpl( LibraryDependencyMirror(
isImport: false, isImport: false,
isDeferred: false, isDeferred: false,
sourceLibrary: sourceLibrary, sourceLibrary: sourceLibrary,
@ -511,11 +496,12 @@ class RuntimeReflector {
} }
/// Returns a mirror on the current isolate. /// Returns a mirror on the current isolate.
IsolateMirror get currentIsolate => _mirrorSystem.isolate; IsolateMirrorContract get currentIsolate => _mirrorSystem.isolate;
/// Creates a mirror for another isolate. /// Creates a mirror for another isolate.
IsolateMirror reflectIsolate(isolate.Isolate isolate, String debugName) { IsolateMirrorContract reflectIsolate(
return IsolateMirrorImpl.other( isolate.Isolate isolate, String debugName) {
return IsolateMirror.other(
isolate, isolate,
debugName, debugName,
reflectLibrary(Uri.parse('dart:core')), reflectLibrary(Uri.parse('dart:core')),

View file

@ -1,10 +1,5 @@
import 'dart:core'; import 'dart:core';
import '../metadata.dart'; import 'package:platform_reflection/mirrors.dart';
import 'reflector.dart';
import '../mirrors.dart';
import '../mirrors/mirror_system_impl.dart';
import '../mirrors/special_types.dart';
import '../exceptions.dart';
/// Runtime scanner that analyzes types and extracts their metadata. /// Runtime scanner that analyzes types and extracts their metadata.
class Scanner { class Scanner {
@ -22,7 +17,7 @@ class Scanner {
Reflector.register(type); Reflector.register(type);
// Get mirror system and analyze type // Get mirror system and analyze type
final mirrorSystem = MirrorSystemImpl.current(); //final mirrorSystem = MirrorSystem.current();
final typeInfo = TypeAnalyzer.analyze(type); final typeInfo = TypeAnalyzer.analyze(type);
// Convert properties, methods, and constructors to metadata // Convert properties, methods, and constructors to metadata

View file

@ -1,4 +1,4 @@
import 'exceptions.dart'; import 'package:platform_reflection/mirrors.dart';
/// Represents metadata about a type parameter. /// Represents metadata about a type parameter.
class TypeParameterMetadata { class TypeParameterMetadata {

View file

@ -1,14 +1,9 @@
import 'dart:core'; import 'dart:core';
import 'mirrors.dart'; import 'package:platform_contracts/contracts.dart';
import 'mirrors/class_mirror_impl.dart'; import 'package:platform_reflection/mirrors.dart';
import 'mirrors/instance_mirror_impl.dart';
import 'mirrors/library_mirror_impl.dart';
import 'mirrors/type_mirror_impl.dart';
import 'mirrors/isolate_mirror_impl.dart';
import 'mirrors/special_types.dart';
/// The default implementation of [MirrorSystem]. /// The default implementation of [MirrorSystemContract].
class RuntimeMirrorSystem implements MirrorSystem { class RuntimeMirrorSystem implements MirrorSystemContract {
/// The singleton instance of the mirror system. /// The singleton instance of the mirror system.
static final instance = RuntimeMirrorSystem._(); static final instance = RuntimeMirrorSystem._();
@ -16,16 +11,16 @@ class RuntimeMirrorSystem implements MirrorSystem {
_initializeRootLibrary(); _initializeRootLibrary();
} }
final Map<Uri, LibraryMirror> _libraries = {}; final Map<Uri, LibraryMirrorContract> _libraries = {};
final Map<Type, ClassMirror> _classes = {}; final Map<Type, ClassMirrorContract> _classes = {};
final Map<Type, TypeMirror> _types = {}; final Map<Type, TypeMirrorContract> _types = {};
late final LibraryMirror _rootLibrary; late final LibraryMirrorContract _rootLibrary;
@override @override
Map<Uri, LibraryMirror> get libraries => Map.unmodifiable(_libraries); Map<Uri, LibraryMirrorContract> get libraries => Map.unmodifiable(_libraries);
@override @override
LibraryMirror findLibrary(Symbol libraryName) { LibraryMirrorContract findLibrary(Symbol libraryName) {
final lib = _libraries.values.firstWhere( final lib = _libraries.values.firstWhere(
(lib) => lib.qualifiedName == libraryName, (lib) => lib.qualifiedName == libraryName,
orElse: () => throw ArgumentError('Library not found: $libraryName'), orElse: () => throw ArgumentError('Library not found: $libraryName'),
@ -34,30 +29,31 @@ class RuntimeMirrorSystem implements MirrorSystem {
} }
@override @override
IsolateMirror get isolate => IsolateMirrorImpl.current(_rootLibrary); IsolateMirrorContract get isolate => IsolateMirror.current(_rootLibrary);
@override @override
TypeMirror get dynamicType => _getOrCreateTypeMirror(dynamic); TypeMirrorContract get dynamicType => _getOrCreateTypeMirror(dynamic);
@override @override
TypeMirror get voidType => _getOrCreateTypeMirror(VoidType); TypeMirrorContract get voidType => _getOrCreateTypeMirror(VoidType);
@override @override
TypeMirror get neverType => _getOrCreateTypeMirror(NeverType); TypeMirrorContract get neverType => _getOrCreateTypeMirror(NeverType);
/// Creates a mirror reflecting [reflectee]. /// Creates a mirror reflecting [reflectee].
InstanceMirror reflect(Object reflectee) { InstanceMirrorContract reflect(Object reflectee) {
return InstanceMirrorImpl( return InstanceMirror(
reflectee: reflectee, reflectee: reflectee,
type: reflectClass(reflectee.runtimeType), type: reflectClass(reflectee.runtimeType),
); );
} }
/// Creates a mirror reflecting the class [key]. /// Creates a mirror reflecting the class [key].
ClassMirror reflectClass(Type key) { @override
ClassMirrorContract reflectClass(Type key) {
return _classes.putIfAbsent( return _classes.putIfAbsent(
key, key,
() => ClassMirrorImpl( () => ClassMirror(
type: key, type: key,
name: key.toString(), name: key.toString(),
owner: _rootLibrary, owner: _rootLibrary,
@ -70,14 +66,15 @@ class RuntimeMirrorSystem implements MirrorSystem {
} }
/// Creates a mirror reflecting the type [key]. /// Creates a mirror reflecting the type [key].
TypeMirror reflectType(Type key) { @override
TypeMirrorContract reflectType(Type key) {
return _getOrCreateTypeMirror(key); return _getOrCreateTypeMirror(key);
} }
TypeMirror _getOrCreateTypeMirror(Type type) { TypeMirrorContract _getOrCreateTypeMirror(Type type) {
return _types.putIfAbsent( return _types.putIfAbsent(
type, type,
() => TypeMirrorImpl( () => TypeMirror(
type: type, type: type,
name: type.toString(), name: type.toString(),
owner: _rootLibrary, owner: _rootLibrary,
@ -87,7 +84,7 @@ class RuntimeMirrorSystem implements MirrorSystem {
} }
void _initializeRootLibrary() { void _initializeRootLibrary() {
_rootLibrary = LibraryMirrorImpl.withDeclarations( _rootLibrary = LibraryMirror.withDeclarations(
name: 'dart.core', name: 'dart.core',
uri: Uri.parse('dart:core'), uri: Uri.parse('dart:core'),
); );
@ -96,16 +93,16 @@ class RuntimeMirrorSystem implements MirrorSystem {
} }
/// The current mirror system. /// The current mirror system.
MirrorSystem currentMirrorSystem() => RuntimeMirrorSystem.instance; MirrorSystemContract currentMirrorSystem() => RuntimeMirrorSystem.instance;
/// Reflects an instance. /// Reflects an instance.
InstanceMirror reflect(Object reflectee) => InstanceMirrorContract reflect(Object reflectee) =>
RuntimeMirrorSystem.instance.reflect(reflectee); RuntimeMirrorSystem.instance.reflect(reflectee);
/// Reflects a class. /// Reflects a class.
ClassMirror reflectClass(Type key) => ClassMirrorContract reflectClass(Type key) =>
RuntimeMirrorSystem.instance.reflectClass(key); RuntimeMirrorSystem.instance.reflectClass(key);
/// Reflects a type. /// Reflects a type.
TypeMirror reflectType(Type key) => TypeMirrorContract reflectType(Type key) =>
RuntimeMirrorSystem.instance.reflectType(key); RuntimeMirrorSystem.instance.reflectType(key);

View file

@ -1,61 +0,0 @@
/// Basic reflection in Dart, with support for introspection and dynamic invocation.
library mirrors;
import 'package:platform_contracts/contracts.dart';
export 'package:platform_contracts/contracts.dart'
show
Mirror,
DeclarationMirror,
ObjectMirror,
InstanceMirror,
TypeMirror,
ClassMirror,
LibraryMirror,
MethodMirror,
VariableMirror,
ParameterMirror,
TypeVariableMirror,
LibraryDependencyMirror,
CombinatorMirror;
export 'mirrors/mirrors.dart';
/// An [IsolateMirror] reflects an isolate.
abstract class IsolateMirror implements Mirror {
/// A unique name used to refer to the isolate in debugging messages.
String get debugName;
/// Whether this mirror reflects the currently running isolate.
bool get isCurrent;
/// The root library for the reflected isolate.
LibraryMirror get rootLibrary;
}
/// A [MirrorSystem] is the main interface used to reflect on a set of libraries.
abstract class MirrorSystem {
/// All libraries known to the mirror system.
Map<Uri, LibraryMirror> get libraries;
/// Returns the unique library with the specified name.
LibraryMirror findLibrary(Symbol libraryName);
/// Returns a mirror for the specified class.
ClassMirror reflectClass(Type type);
/// Returns a mirror for the specified type.
TypeMirror reflectType(Type type);
/// A mirror on the isolate associated with this mirror system.
IsolateMirror get isolate;
/// A mirror on the dynamic type.
TypeMirror get dynamicType;
/// A mirror on the void type.
TypeMirror get voidType;
/// A mirror on the Never type.
TypeMirror get neverType;
}

View file

@ -1,31 +1,31 @@
import 'package:meta/meta.dart'; import 'package:meta/meta.dart';
import '../mirrors.dart'; import 'package:platform_contracts/contracts.dart';
/// Base class for mirrors that have an owner. /// Base class for mirrors that have an owner.
abstract class MutableOwnerMirror implements DeclarationMirror { abstract class MutableOwnerMirror implements DeclarationMirrorContract {
DeclarationMirror? _owner; DeclarationMirrorContract? _owner;
/// Sets the owner of this mirror. /// Sets the owner of this mirror.
@protected @protected
void setOwner(DeclarationMirror? owner) { void setOwner(DeclarationMirrorContract? owner) {
_owner = owner; _owner = owner;
} }
@override @override
DeclarationMirror? get owner => _owner; DeclarationMirrorContract? get owner => _owner;
} }
/// Base class for mirrors that have a type. /// Base class for mirrors that have a type.
abstract class TypedMirror extends MutableOwnerMirror { abstract class TypedMirror extends MutableOwnerMirror {
final Type _type; final Type _type;
final String _name; final String _name;
final List<InstanceMirror> _metadata; final List<InstanceMirrorContract> _metadata;
TypedMirror({ TypedMirror({
required Type type, required Type type,
required String name, required String name,
DeclarationMirror? owner, DeclarationMirrorContract? owner,
List<InstanceMirror> metadata = const [], List<InstanceMirrorContract> metadata = const [],
}) : _type = type, }) : _type = type,
_name = name, _name = name,
_metadata = metadata { _metadata = metadata {
@ -54,5 +54,5 @@ abstract class TypedMirror extends MutableOwnerMirror {
bool get isTopLevel => owner == null; bool get isTopLevel => owner == null;
@override @override
List<InstanceMirror> get metadata => List.unmodifiable(_metadata); List<InstanceMirrorContract> get metadata => List.unmodifiable(_metadata);
} }

View file

@ -1,23 +1,16 @@
import '../metadata.dart'; import 'package:platform_contracts/contracts.dart';
import '../mirrors.dart'; import 'package:platform_reflection/mirrors.dart';
import '../exceptions.dart';
import '../core/reflector.dart';
import 'base_mirror.dart';
import 'instance_mirror_impl.dart';
import 'method_mirror_impl.dart';
import 'mirror_system_impl.dart';
import 'type_mirror_impl.dart';
/// Implementation of [ClassMirror]. /// Implementation of [ClassMirrorContract].
class ClassMirrorImpl extends TypeMirrorImpl implements ClassMirror { class ClassMirror extends TypeMirror implements ClassMirrorContract {
@override @override
final Map<Symbol, DeclarationMirror> declarations; final Map<Symbol, DeclarationMirrorContract> declarations;
@override @override
final Map<Symbol, MethodMirror> instanceMembers; final Map<Symbol, MethodMirrorContract> instanceMembers;
@override @override
final Map<Symbol, MethodMirror> staticMembers; final Map<Symbol, MethodMirrorContract> staticMembers;
@override @override
final bool isAbstract; final bool isAbstract;
@ -26,19 +19,19 @@ class ClassMirrorImpl extends TypeMirrorImpl implements ClassMirror {
final bool isEnum; final bool isEnum;
@override @override
final ClassMirror? superclass; final ClassMirrorContract? superclass;
@override @override
final List<ClassMirror> superinterfaces; final List<ClassMirrorContract> superinterfaces;
ClassMirrorImpl({ ClassMirror({
required Type type, required Type type,
required String name, required String name,
required DeclarationMirror? owner, required DeclarationMirrorContract? owner,
required this.declarations, required this.declarations,
required this.instanceMembers, required this.instanceMembers,
required this.staticMembers, required this.staticMembers,
required List<InstanceMirror> metadata, required List<InstanceMirrorContract> metadata,
this.isAbstract = false, this.isAbstract = false,
this.isEnum = false, this.isEnum = false,
this.superclass, this.superclass,
@ -57,19 +50,19 @@ class ClassMirrorImpl extends TypeMirrorImpl implements ClassMirror {
} }
@override @override
bool isSubclassOf(ClassMirror other) { bool isSubclassOf(ClassMirrorContract other) {
var current = this; var current = this;
while (current.superclass != null) { while (current.superclass != null) {
if (current.superclass == other) { if (current.superclass == other) {
return true; return true;
} }
current = current.superclass as ClassMirrorImpl; current = current.superclass as ClassMirror;
} }
return false; return false;
} }
@override @override
InstanceMirror newInstance( InstanceMirrorContract newInstance(
Symbol constructorName, Symbol constructorName,
List<dynamic> positionalArguments, [ List<dynamic> positionalArguments, [
Map<Symbol, dynamic>? namedArguments, Map<Symbol, dynamic>? namedArguments,
@ -126,7 +119,7 @@ class ClassMirrorImpl extends TypeMirrorImpl implements ClassMirror {
'Failed to create instance: creator returned null'); 'Failed to create instance: creator returned null');
} }
return InstanceMirrorImpl( return InstanceMirror(
reflectee: instance, reflectee: instance,
type: this, type: this,
); );
@ -136,7 +129,8 @@ class ClassMirrorImpl extends TypeMirrorImpl implements ClassMirror {
} }
@override @override
InstanceMirror invoke(Symbol memberName, List<dynamic> positionalArguments, InstanceMirrorContract invoke(
Symbol memberName, List<dynamic> positionalArguments,
[Map<Symbol, dynamic>? namedArguments]) { [Map<Symbol, dynamic>? namedArguments]) {
try { try {
// Get method metadata // Get method metadata
@ -174,7 +168,7 @@ class ClassMirrorImpl extends TypeMirrorImpl implements ClassMirror {
namedArguments, namedArguments,
); );
return InstanceMirrorImpl( return InstanceMirror(
reflectee: result, reflectee: result,
type: this, type: this,
); );
@ -184,7 +178,7 @@ class ClassMirrorImpl extends TypeMirrorImpl implements ClassMirror {
} }
@override @override
InstanceMirror getField(Symbol fieldName) { InstanceMirrorContract getField(Symbol fieldName) {
final declaration = declarations[fieldName]; final declaration = declarations[fieldName];
if (declaration == null) { if (declaration == null) {
throw NoSuchMethodError.withInvocation( throw NoSuchMethodError.withInvocation(
@ -195,7 +189,7 @@ class ClassMirrorImpl extends TypeMirrorImpl implements ClassMirror {
try { try {
final value = (type as dynamic)[_symbolToString(fieldName)]; final value = (type as dynamic)[_symbolToString(fieldName)];
return InstanceMirrorImpl( return InstanceMirror(
reflectee: value, reflectee: value,
type: this, type: this,
); );
@ -205,7 +199,7 @@ class ClassMirrorImpl extends TypeMirrorImpl implements ClassMirror {
} }
@override @override
InstanceMirror setField(Symbol fieldName, dynamic value) { InstanceMirrorContract setField(Symbol fieldName, dynamic value) {
final declaration = declarations[fieldName]; final declaration = declarations[fieldName];
if (declaration == null) { if (declaration == null) {
throw NoSuchMethodError.withInvocation( throw NoSuchMethodError.withInvocation(
@ -216,7 +210,7 @@ class ClassMirrorImpl extends TypeMirrorImpl implements ClassMirror {
try { try {
(type as dynamic)[_symbolToString(fieldName)] = value; (type as dynamic)[_symbolToString(fieldName)] = value;
return InstanceMirrorImpl( return InstanceMirror(
reflectee: value, reflectee: value,
type: this, type: this,
); );
@ -228,7 +222,7 @@ class ClassMirrorImpl extends TypeMirrorImpl implements ClassMirror {
@override @override
bool operator ==(Object other) => bool operator ==(Object other) =>
identical(this, other) || identical(this, other) ||
other is ClassMirrorImpl && other is ClassMirror &&
runtimeType == other.runtimeType && runtimeType == other.runtimeType &&
type == other.type; type == other.type;

View file

@ -1,11 +1,11 @@
import '../mirrors.dart'; import 'package:platform_contracts/contracts.dart';
/// Implementation of [CombinatorMirror] that provides reflection on show/hide combinators. /// Implementation of [CombinatorMirrorContract] that provides reflection on show/hide combinators.
class CombinatorMirrorImpl implements CombinatorMirror { class CombinatorMirror implements CombinatorMirrorContract {
final List<Symbol> _identifiers; final List<Symbol> _identifiers;
final bool _isShow; final bool _isShow;
CombinatorMirrorImpl({ CombinatorMirror({
required List<Symbol> identifiers, required List<Symbol> identifiers,
required bool isShow, required bool isShow,
}) : _identifiers = identifiers, }) : _identifiers = identifiers,
@ -23,7 +23,7 @@ class CombinatorMirrorImpl implements CombinatorMirror {
@override @override
bool operator ==(Object other) { bool operator ==(Object other) {
if (identical(this, other)) return true; if (identical(this, other)) return true;
if (other is! CombinatorMirrorImpl) return false; if (other is! CombinatorMirror) return false;
return _identifiers == other._identifiers && _isShow == other._isShow; return _identifiers == other._identifiers && _isShow == other._isShow;
} }

View file

@ -1,21 +1,20 @@
import 'dart:core'; import 'dart:core';
import '../mirrors.dart'; import 'package:platform_contracts/contracts.dart';
import '../exceptions.dart'; import 'package:platform_reflection/mirrors.dart';
import '../core/reflector.dart';
/// Implementation of [InstanceMirror] that provides reflection on instances. /// Implementation of [InstanceMirrorContract] that provides reflection on instances.
class InstanceMirrorImpl implements InstanceMirror { class InstanceMirror implements InstanceMirrorContract {
final Object _reflectee; final Object _reflectee;
final ClassMirror _type; final ClassMirrorContract _type;
InstanceMirrorImpl({ InstanceMirror({
required Object reflectee, required Object reflectee,
required ClassMirror type, required ClassMirrorContract type,
}) : _reflectee = reflectee, }) : _reflectee = reflectee,
_type = type; _type = type;
@override @override
ClassMirror get type => _type; ClassMirrorContract get type => _type;
@override @override
bool get hasReflectee => true; bool get hasReflectee => true;
@ -24,7 +23,7 @@ class InstanceMirrorImpl implements InstanceMirror {
dynamic get reflectee => _reflectee; dynamic get reflectee => _reflectee;
@override @override
InstanceMirror invoke(Symbol memberName, List positionalArguments, InstanceMirrorContract invoke(Symbol memberName, List positionalArguments,
[Map<Symbol, dynamic> namedArguments = const {}]) { [Map<Symbol, dynamic> namedArguments = const {}]) {
// Get method metadata // Get method metadata
final methods = Reflector.getMethodMetadata(_reflectee.runtimeType); final methods = Reflector.getMethodMetadata(_reflectee.runtimeType);
@ -79,7 +78,7 @@ class InstanceMirrorImpl implements InstanceMirror {
default: default:
throw ReflectionException('Method $methodName not implemented'); throw ReflectionException('Method $methodName not implemented');
} }
return InstanceMirrorImpl( return InstanceMirror(
reflectee: result ?? '', reflectee: result ?? '',
type: _type, type: _type,
); );
@ -89,7 +88,7 @@ class InstanceMirrorImpl implements InstanceMirror {
} }
@override @override
InstanceMirror getField(Symbol fieldName) { InstanceMirrorContract getField(Symbol fieldName) {
// Get property metadata // Get property metadata
final properties = Reflector.getPropertyMetadata(_reflectee.runtimeType); final properties = Reflector.getPropertyMetadata(_reflectee.runtimeType);
if (properties == null) { if (properties == null) {
@ -135,7 +134,7 @@ class InstanceMirrorImpl implements InstanceMirror {
default: default:
throw ReflectionException('Property $propertyName not implemented'); throw ReflectionException('Property $propertyName not implemented');
} }
return InstanceMirrorImpl( return InstanceMirror(
reflectee: value ?? '', reflectee: value ?? '',
type: _type, type: _type,
); );
@ -145,7 +144,7 @@ class InstanceMirrorImpl implements InstanceMirror {
} }
@override @override
InstanceMirror setField(Symbol fieldName, dynamic value) { InstanceMirrorContract setField(Symbol fieldName, dynamic value) {
// Get property metadata // Get property metadata
final properties = Reflector.getPropertyMetadata(_reflectee.runtimeType); final properties = Reflector.getPropertyMetadata(_reflectee.runtimeType);
if (properties == null) { if (properties == null) {
@ -194,7 +193,7 @@ class InstanceMirrorImpl implements InstanceMirror {
default: default:
throw ReflectionException('Property $propertyName not implemented'); throw ReflectionException('Property $propertyName not implemented');
} }
return InstanceMirrorImpl( return InstanceMirror(
reflectee: value, reflectee: value,
type: _type, type: _type,
); );
@ -206,7 +205,7 @@ class InstanceMirrorImpl implements InstanceMirror {
@override @override
bool operator ==(Object other) { bool operator ==(Object other) {
if (identical(this, other)) return true; if (identical(this, other)) return true;
if (other is! InstanceMirrorImpl) return false; if (other is! InstanceMirror) return false;
return identical(_reflectee, other._reflectee) && _type == other._type; return identical(_reflectee, other._reflectee) && _type == other._type;
} }
@ -224,22 +223,22 @@ class InstanceMirrorImpl implements InstanceMirror {
} }
} }
/// Implementation of [InstanceMirror] for closures. /// Implementation of [InstanceMirrorContract] for closures.
class ClosureMirrorImpl extends InstanceMirrorImpl { class ClosureMirrorImpl extends InstanceMirror {
final MethodMirror _function; final MethodMirrorContract _function;
ClosureMirrorImpl({ ClosureMirrorImpl({
required Object reflectee, required Object reflectee,
required ClassMirror type, required ClassMirrorContract type,
required MethodMirror function, required MethodMirrorContract function,
}) : _function = function, }) : _function = function,
super(reflectee: reflectee, type: type); super(reflectee: reflectee, type: type);
/// The function this closure represents. /// The function this closure represents.
MethodMirror get function => _function; MethodMirrorContract get function => _function;
/// Applies this closure with the given arguments. /// Applies this closure with the given arguments.
InstanceMirror apply(List positionalArguments, InstanceMirrorContract apply(List positionalArguments,
[Map<Symbol, dynamic> namedArguments = const {}]) { [Map<Symbol, dynamic> namedArguments = const {}]) {
final closure = reflectee as Function; final closure = reflectee as Function;
final result = Function.apply( final result = Function.apply(
@ -247,7 +246,7 @@ class ClosureMirrorImpl extends InstanceMirrorImpl {
positionalArguments, positionalArguments,
namedArguments, namedArguments,
); );
return InstanceMirrorImpl( return InstanceMirror(
reflectee: result ?? '', reflectee: result ?? '',
type: type, type: type,
); );
@ -269,11 +268,11 @@ class ClosureMirrorImpl extends InstanceMirrorImpl {
String toString() => 'ClosureMirror on ${_reflectee.runtimeType}'; String toString() => 'ClosureMirror on ${_reflectee.runtimeType}';
} }
/// Implementation of [InstanceMirror] for simple values. /// Implementation of [InstanceMirrorContract] for simple values.
class ValueMirrorImpl extends InstanceMirrorImpl { class ValueMirrorImpl extends InstanceMirror {
ValueMirrorImpl({ ValueMirrorImpl({
required Object reflectee, required Object reflectee,
required ClassMirror type, required ClassMirrorContract type,
}) : super(reflectee: reflectee, type: type); }) : super(reflectee: reflectee, type: type);
@override @override

View file

@ -1,19 +1,18 @@
import 'dart:core'; import 'dart:core';
import 'dart:isolate' as isolate; import 'dart:isolate' as isolate;
import '../mirrors.dart'; import 'package:platform_contracts/contracts.dart';
import 'library_mirror_impl.dart';
/// Implementation of [IsolateMirror] that provides reflection on isolates. /// Implementation of [IsolateMirrorContract] that provides reflection on isolates.
class IsolateMirrorImpl implements IsolateMirror { class IsolateMirror implements IsolateMirrorContract {
final String _debugName; final String _debugName;
final bool _isCurrent; final bool _isCurrent;
final LibraryMirror _rootLibrary; final LibraryMirrorContract _rootLibrary;
final isolate.Isolate? _underlyingIsolate; final isolate.Isolate? _underlyingIsolate;
IsolateMirrorImpl({ IsolateMirror({
required String debugName, required String debugName,
required bool isCurrent, required bool isCurrent,
required LibraryMirror rootLibrary, required LibraryMirrorContract rootLibrary,
isolate.Isolate? underlyingIsolate, isolate.Isolate? underlyingIsolate,
}) : _debugName = debugName, }) : _debugName = debugName,
_isCurrent = isCurrent, _isCurrent = isCurrent,
@ -21,8 +20,8 @@ class IsolateMirrorImpl implements IsolateMirror {
_underlyingIsolate = underlyingIsolate; _underlyingIsolate = underlyingIsolate;
/// Creates a mirror for the current isolate. /// Creates a mirror for the current isolate.
factory IsolateMirrorImpl.current(LibraryMirror rootLibrary) { factory IsolateMirror.current(LibraryMirrorContract rootLibrary) {
return IsolateMirrorImpl( return IsolateMirror(
debugName: 'main', debugName: 'main',
isCurrent: true, isCurrent: true,
rootLibrary: rootLibrary, rootLibrary: rootLibrary,
@ -31,12 +30,12 @@ class IsolateMirrorImpl implements IsolateMirror {
} }
/// Creates a mirror for another isolate. /// Creates a mirror for another isolate.
factory IsolateMirrorImpl.other( factory IsolateMirror.other(
isolate.Isolate underlyingIsolate, isolate.Isolate underlyingIsolate,
String debugName, String debugName,
LibraryMirror rootLibrary, LibraryMirrorContract rootLibrary,
) { ) {
return IsolateMirrorImpl( return IsolateMirror(
debugName: debugName, debugName: debugName,
isCurrent: false, isCurrent: false,
rootLibrary: rootLibrary, rootLibrary: rootLibrary,
@ -51,7 +50,7 @@ class IsolateMirrorImpl implements IsolateMirror {
bool get isCurrent => _isCurrent; bool get isCurrent => _isCurrent;
@override @override
LibraryMirror get rootLibrary => _rootLibrary; LibraryMirrorContract get rootLibrary => _rootLibrary;
/// The underlying isolate, if this mirror reflects a non-current isolate. /// The underlying isolate, if this mirror reflects a non-current isolate.
isolate.Isolate? get underlyingIsolate => _underlyingIsolate; isolate.Isolate? get underlyingIsolate => _underlyingIsolate;
@ -59,7 +58,7 @@ class IsolateMirrorImpl implements IsolateMirror {
@override @override
bool operator ==(Object other) { bool operator ==(Object other) {
if (identical(this, other)) return true; if (identical(this, other)) return true;
if (other is! IsolateMirrorImpl) return false; if (other is! IsolateMirror) return false;
// Only compare debug name and isCurrent flag // Only compare debug name and isCurrent flag
// Two mirrors pointing to the same isolate should be equal // Two mirrors pointing to the same isolate should be equal

View file

@ -1,21 +1,21 @@
import '../mirrors.dart'; import 'package:platform_contracts/contracts.dart';
/// Implementation of [LibraryDependencyMirror] that provides reflection on library dependencies. /// Implementation of [LibraryDependencyMirrorContract] that provides reflection on library dependencies.
class LibraryDependencyMirrorImpl implements LibraryDependencyMirror { class LibraryDependencyMirror implements LibraryDependencyMirrorContract {
final bool _isImport; final bool _isImport;
final bool _isDeferred; final bool _isDeferred;
final LibraryMirror _sourceLibrary; final LibraryMirrorContract _sourceLibrary;
final LibraryMirror? _targetLibrary; final LibraryMirrorContract? _targetLibrary;
final Symbol? _prefix; final Symbol? _prefix;
final List<CombinatorMirror> _combinators; final List<CombinatorMirrorContract> _combinators;
LibraryDependencyMirrorImpl({ LibraryDependencyMirror({
required bool isImport, required bool isImport,
required bool isDeferred, required bool isDeferred,
required LibraryMirror sourceLibrary, required LibraryMirrorContract sourceLibrary,
LibraryMirror? targetLibrary, LibraryMirrorContract? targetLibrary,
Symbol? prefix, Symbol? prefix,
List<CombinatorMirror> combinators = const [], List<CombinatorMirrorContract> combinators = const [],
}) : _isImport = isImport, }) : _isImport = isImport,
_isDeferred = isDeferred, _isDeferred = isDeferred,
_sourceLibrary = sourceLibrary, _sourceLibrary = sourceLibrary,
@ -33,21 +33,22 @@ class LibraryDependencyMirrorImpl implements LibraryDependencyMirror {
bool get isDeferred => _isDeferred; bool get isDeferred => _isDeferred;
@override @override
LibraryMirror get sourceLibrary => _sourceLibrary; LibraryMirrorContract get sourceLibrary => _sourceLibrary;
@override @override
LibraryMirror? get targetLibrary => _targetLibrary; LibraryMirrorContract? get targetLibrary => _targetLibrary;
@override @override
Symbol? get prefix => _prefix; Symbol? get prefix => _prefix;
@override @override
List<CombinatorMirror> get combinators => List.unmodifiable(_combinators); List<CombinatorMirrorContract> get combinators =>
List.unmodifiable(_combinators);
@override @override
bool operator ==(Object other) { bool operator ==(Object other) {
if (identical(this, other)) return true; if (identical(this, other)) return true;
if (other is! LibraryDependencyMirrorImpl) return false; if (other is! LibraryDependencyMirror) return false;
return _isImport == other._isImport && return _isImport == other._isImport &&
_isDeferred == other._isDeferred && _isDeferred == other._isDeferred &&

View file

@ -1,31 +1,21 @@
import 'dart:core'; import 'dart:core';
import '../mirrors.dart'; import 'package:platform_contracts/contracts.dart';
import '../core/library_scanner.dart'; import 'package:platform_reflection/mirrors.dart';
import 'base_mirror.dart';
import 'library_dependency_mirror_impl.dart';
import 'method_mirror_impl.dart';
import 'variable_mirror_impl.dart';
import 'type_mirror_impl.dart';
import 'parameter_mirror_impl.dart';
import 'instance_mirror_impl.dart';
import 'class_mirror_impl.dart';
import '../core/reflector.dart';
import '../core/runtime_reflector.dart';
/// Implementation of [LibraryMirror] that provides reflection on libraries. /// Implementation of [LibraryMirrorContract] that provides reflection on libraries.
class LibraryMirrorImpl extends TypedMirror implements LibraryMirror { class LibraryMirror extends TypedMirror implements LibraryMirrorContract {
final Uri _uri; final Uri _uri;
final Map<Symbol, DeclarationMirror> _declarations; final Map<Symbol, DeclarationMirrorContract> _declarations;
final List<LibraryDependencyMirror> _libraryDependencies; final List<LibraryDependencyMirrorContract> _libraryDependencies;
final Map<Symbol, dynamic> _topLevelValues; final Map<Symbol, dynamic> _topLevelValues;
LibraryMirrorImpl({ LibraryMirror({
required String name, required String name,
required Uri uri, required Uri uri,
DeclarationMirror? owner, DeclarationMirrorContract? owner,
Map<Symbol, DeclarationMirror>? declarations, Map<Symbol, DeclarationMirrorContract>? declarations,
List<LibraryDependencyMirror> libraryDependencies = const [], List<LibraryDependencyMirrorContract> libraryDependencies = const [],
List<InstanceMirror> metadata = const [], List<InstanceMirrorContract> metadata = const [],
Map<Symbol, dynamic>? topLevelValues, Map<Symbol, dynamic>? topLevelValues,
}) : _uri = uri, }) : _uri = uri,
_declarations = declarations ?? {}, _declarations = declarations ?? {},
@ -39,20 +29,20 @@ class LibraryMirrorImpl extends TypedMirror implements LibraryMirror {
); );
/// Factory constructor that creates a library mirror with declarations from scanning /// Factory constructor that creates a library mirror with declarations from scanning
factory LibraryMirrorImpl.withDeclarations({ factory LibraryMirror.withDeclarations({
required String name, required String name,
required Uri uri, required Uri uri,
DeclarationMirror? owner, DeclarationMirrorContract? owner,
List<LibraryDependencyMirror> libraryDependencies = const [], List<LibraryDependencyMirrorContract> libraryDependencies = const [],
List<InstanceMirror> metadata = const [], List<InstanceMirrorContract> metadata = const [],
}) { }) {
// Scan library to get declarations // Scan library to get declarations
final libraryInfo = LibraryScanner.scanLibrary(uri); final libraryInfo = LibraryScanner.scanLibrary(uri);
final declarations = <Symbol, DeclarationMirror>{}; final declarations = <Symbol, DeclarationMirrorContract>{};
final topLevelValues = <Symbol, dynamic>{}; final topLevelValues = <Symbol, dynamic>{};
// Create temporary library for owner references // Create temporary library for owner references
final tempLibrary = LibraryMirrorImpl( final tempLibrary = LibraryMirror(
name: name, name: name,
uri: uri, uri: uri,
owner: owner, owner: owner,
@ -63,19 +53,19 @@ class LibraryMirrorImpl extends TypedMirror implements LibraryMirror {
// Add top-level function declarations // Add top-level function declarations
for (final function in libraryInfo.topLevelFunctions) { for (final function in libraryInfo.topLevelFunctions) {
if (!function.isPrivate || uri == tempLibrary.uri) { if (!function.isPrivate || uri == tempLibrary.uri) {
declarations[Symbol(function.name)] = MethodMirrorImpl( declarations[Symbol(function.name)] = MethodMirror(
name: function.name, name: function.name,
owner: tempLibrary, owner: tempLibrary,
returnType: TypeMirrorImpl( returnType: TypeMirror(
type: function.returnType, type: function.returnType,
name: function.returnType.toString(), name: function.returnType.toString(),
owner: tempLibrary, owner: tempLibrary,
metadata: const [], metadata: const [],
), ),
parameters: function.parameters parameters: function.parameters
.map((param) => ParameterMirrorImpl( .map((param) => ParameterMirror(
name: param.name, name: param.name,
type: TypeMirrorImpl( type: TypeMirror(
type: param.type, type: param.type,
name: param.type.toString(), name: param.type.toString(),
owner: tempLibrary, owner: tempLibrary,
@ -96,9 +86,9 @@ class LibraryMirrorImpl extends TypedMirror implements LibraryMirror {
// Add top-level variable declarations // Add top-level variable declarations
for (final variable in libraryInfo.topLevelVariables) { for (final variable in libraryInfo.topLevelVariables) {
if (!variable.isPrivate || uri == tempLibrary.uri) { if (!variable.isPrivate || uri == tempLibrary.uri) {
declarations[Symbol(variable.name)] = VariableMirrorImpl( declarations[Symbol(variable.name)] = VariableMirror(
name: variable.name, name: variable.name,
type: TypeMirrorImpl( type: TypeMirror(
type: variable.type, type: variable.type,
name: variable.type.toString(), name: variable.type.toString(),
owner: tempLibrary, owner: tempLibrary,
@ -124,15 +114,15 @@ class LibraryMirrorImpl extends TypedMirror implements LibraryMirror {
} }
// Create library dependencies // Create library dependencies
final dependencies = <LibraryDependencyMirror>[]; final dependencies = <LibraryDependencyMirrorContract>[];
// Add imports // Add imports
for (final dep in libraryInfo.dependencies) { for (final dep in libraryInfo.dependencies) {
dependencies.add(LibraryDependencyMirrorImpl( dependencies.add(LibraryDependencyMirror(
isImport: true, isImport: true,
isDeferred: dep.isDeferred, isDeferred: dep.isDeferred,
sourceLibrary: tempLibrary, sourceLibrary: tempLibrary,
targetLibrary: LibraryMirrorImpl.withDeclarations( targetLibrary: LibraryMirror.withDeclarations(
name: dep.uri.toString(), name: dep.uri.toString(),
uri: dep.uri, uri: dep.uri,
owner: tempLibrary, owner: tempLibrary,
@ -144,11 +134,11 @@ class LibraryMirrorImpl extends TypedMirror implements LibraryMirror {
// Add exports // Add exports
for (final dep in libraryInfo.exports) { for (final dep in libraryInfo.exports) {
dependencies.add(LibraryDependencyMirrorImpl( dependencies.add(LibraryDependencyMirror(
isImport: false, isImport: false,
isDeferred: false, isDeferred: false,
sourceLibrary: tempLibrary, sourceLibrary: tempLibrary,
targetLibrary: LibraryMirrorImpl.withDeclarations( targetLibrary: LibraryMirror.withDeclarations(
name: dep.uri.toString(), name: dep.uri.toString(),
uri: dep.uri, uri: dep.uri,
owner: tempLibrary, owner: tempLibrary,
@ -158,7 +148,7 @@ class LibraryMirrorImpl extends TypedMirror implements LibraryMirror {
)); ));
} }
return LibraryMirrorImpl( return LibraryMirror(
name: name, name: name,
uri: uri, uri: uri,
owner: owner, owner: owner,
@ -194,15 +184,15 @@ class LibraryMirrorImpl extends TypedMirror implements LibraryMirror {
Uri get uri => _uri; Uri get uri => _uri;
@override @override
Map<Symbol, DeclarationMirror> get declarations => Map<Symbol, DeclarationMirrorContract> get declarations =>
Map.unmodifiable(_declarations); Map.unmodifiable(_declarations);
@override @override
List<LibraryDependencyMirror> get libraryDependencies => List<LibraryDependencyMirrorContract> get libraryDependencies =>
List.unmodifiable(_libraryDependencies); List.unmodifiable(_libraryDependencies);
@override @override
InstanceMirror invoke(Symbol memberName, List positionalArguments, InstanceMirrorContract invoke(Symbol memberName, List positionalArguments,
[Map<Symbol, dynamic> namedArguments = const {}]) { [Map<Symbol, dynamic> namedArguments = const {}]) {
final member = declarations[memberName]; final member = declarations[memberName];
if (member == null) { if (member == null) {
@ -212,7 +202,7 @@ class LibraryMirrorImpl extends TypedMirror implements LibraryMirror {
); );
} }
if (member is! MethodMirror) { if (member is! MethodMirrorContract) {
throw NoSuchMethodError.withInvocation( throw NoSuchMethodError.withInvocation(
this, this,
Invocation.method(memberName, positionalArguments, namedArguments), Invocation.method(memberName, positionalArguments, namedArguments),
@ -223,7 +213,7 @@ class LibraryMirrorImpl extends TypedMirror implements LibraryMirror {
if (memberName == const Symbol('add')) { if (memberName == const Symbol('add')) {
final a = positionalArguments[0] as int; final a = positionalArguments[0] as int;
final b = positionalArguments[1] as int; final b = positionalArguments[1] as int;
return InstanceMirrorImpl( return InstanceMirror(
reflectee: a + b, reflectee: a + b,
type: _createPrimitiveClassMirror(int, 'int'), type: _createPrimitiveClassMirror(int, 'int'),
); );
@ -234,7 +224,7 @@ class LibraryMirrorImpl extends TypedMirror implements LibraryMirror {
} }
@override @override
InstanceMirror getField(Symbol fieldName) { InstanceMirrorContract getField(Symbol fieldName) {
final member = declarations[fieldName]; final member = declarations[fieldName];
if (member == null) { if (member == null) {
throw NoSuchMethodError.withInvocation( throw NoSuchMethodError.withInvocation(
@ -243,7 +233,7 @@ class LibraryMirrorImpl extends TypedMirror implements LibraryMirror {
); );
} }
if (member is! VariableMirror) { if (member is! VariableMirrorContract) {
throw NoSuchMethodError.withInvocation( throw NoSuchMethodError.withInvocation(
this, this,
Invocation.getter(fieldName), Invocation.getter(fieldName),
@ -257,14 +247,14 @@ class LibraryMirrorImpl extends TypedMirror implements LibraryMirror {
'Top-level variable $fieldName has not been initialized'); 'Top-level variable $fieldName has not been initialized');
} }
return InstanceMirrorImpl( return InstanceMirror(
reflectee: value, reflectee: value,
type: _createPrimitiveClassMirror(member.type.reflectedType, member.name), type: _createPrimitiveClassMirror(member.type.reflectedType, member.name),
); );
} }
@override @override
InstanceMirror setField(Symbol fieldName, dynamic value) { InstanceMirrorContract setField(Symbol fieldName, dynamic value) {
final member = declarations[fieldName]; final member = declarations[fieldName];
if (member == null) { if (member == null) {
throw NoSuchMethodError.withInvocation( throw NoSuchMethodError.withInvocation(
@ -273,7 +263,7 @@ class LibraryMirrorImpl extends TypedMirror implements LibraryMirror {
); );
} }
if (member is! VariableMirror) { if (member is! VariableMirrorContract) {
throw NoSuchMethodError.withInvocation( throw NoSuchMethodError.withInvocation(
this, this,
Invocation.setter(fieldName, [value]), Invocation.setter(fieldName, [value]),
@ -296,15 +286,16 @@ class LibraryMirrorImpl extends TypedMirror implements LibraryMirror {
// Update value in top-level values map // Update value in top-level values map
_topLevelValues[fieldName] = value; _topLevelValues[fieldName] = value;
return InstanceMirrorImpl( return InstanceMirror(
reflectee: value, reflectee: value,
type: _createPrimitiveClassMirror(member.type.reflectedType, member.name), type: _createPrimitiveClassMirror(member.type.reflectedType, member.name),
); );
} }
/// Creates a ClassMirror for a primitive type. /// Creates a ClassMirror for a primitive type.
static ClassMirror _createPrimitiveClassMirror(Type type, String name) { static ClassMirrorContract _createPrimitiveClassMirror(
return ClassMirrorImpl( Type type, String name) {
return ClassMirror(
type: type, type: type,
name: name, name: name,
owner: null, owner: null,
@ -318,7 +309,7 @@ class LibraryMirrorImpl extends TypedMirror implements LibraryMirror {
@override @override
bool operator ==(Object other) { bool operator ==(Object other) {
if (identical(this, other)) return true; if (identical(this, other)) return true;
if (other is! LibraryMirrorImpl) return false; if (other is! LibraryMirror) return false;
return _uri == other._uri && return _uri == other._uri &&
name == other.name && name == other.name &&

View file

@ -1,10 +1,10 @@
import '../mirrors.dart'; import 'package:platform_contracts/contracts.dart';
import 'base_mirror.dart'; import 'package:platform_reflection/mirrors.dart';
/// Implementation of [MethodMirror] that provides reflection on methods. /// Implementation of [MethodMirrorContract] that provides reflection on methods.
class MethodMirrorImpl extends TypedMirror implements MethodMirror { class MethodMirror extends TypedMirror implements MethodMirrorContract {
final TypeMirror _returnType; final TypeMirrorContract _returnType;
final List<ParameterMirror> _parameters; final List<ParameterMirrorContract> _parameters;
final bool _isStatic; final bool _isStatic;
final bool _isAbstract; final bool _isAbstract;
final bool _isSynthetic; final bool _isSynthetic;
@ -16,11 +16,11 @@ class MethodMirrorImpl extends TypedMirror implements MethodMirror {
final bool _isFactoryConstructor; final bool _isFactoryConstructor;
final String? _source; final String? _source;
MethodMirrorImpl({ MethodMirror({
required String name, required String name,
required DeclarationMirror? owner, required DeclarationMirrorContract? owner,
required TypeMirror returnType, required TypeMirrorContract returnType,
required List<ParameterMirror> parameters, required List<ParameterMirrorContract> parameters,
bool isStatic = false, bool isStatic = false,
bool isAbstract = false, bool isAbstract = false,
bool isSynthetic = false, bool isSynthetic = false,
@ -31,7 +31,7 @@ class MethodMirrorImpl extends TypedMirror implements MethodMirror {
bool isRedirectingConstructor = false, bool isRedirectingConstructor = false,
bool isFactoryConstructor = false, bool isFactoryConstructor = false,
String? source, String? source,
List<InstanceMirror> metadata = const [], List<InstanceMirrorContract> metadata = const [],
}) : _returnType = returnType, }) : _returnType = returnType,
_parameters = parameters, _parameters = parameters,
_isStatic = isStatic, _isStatic = isStatic,
@ -52,10 +52,11 @@ class MethodMirrorImpl extends TypedMirror implements MethodMirror {
); );
@override @override
TypeMirror get returnType => _returnType; TypeMirrorContract get returnType => _returnType;
@override @override
List<ParameterMirror> get parameters => List.unmodifiable(_parameters); List<ParameterMirrorContract> get parameters =>
List.unmodifiable(_parameters);
@override @override
bool get isStatic => _isStatic; bool get isStatic => _isStatic;
@ -103,7 +104,7 @@ class MethodMirrorImpl extends TypedMirror implements MethodMirror {
@override @override
bool operator ==(Object other) { bool operator ==(Object other) {
if (identical(this, other)) return true; if (identical(this, other)) return true;
if (other is! MethodMirrorImpl) return false; if (other is! MethodMirror) return false;
return name == other.name && return name == other.name &&
owner == other.owner && owner == other.owner &&

View file

@ -0,0 +1,323 @@
import 'dart:core';
import 'package:platform_contracts/contracts.dart';
import 'package:platform_reflection/mirrors.dart';
/// Implementation of [MirrorSystemContract] that provides reflection on a set of libraries.
class MirrorSystem implements MirrorSystemContract {
static MirrorSystem? _instance;
static MirrorSystem get instance {
return _instance ??= MirrorSystem._();
}
// Add this method back
static MirrorSystem current() {
return instance;
}
final Map<Uri, LibraryMirrorContract> _libraries = {};
final Map<Type, ClassMirrorContract> _classes = {};
final Map<Type, TypeMirrorContract> _types = {};
late final LibraryMirrorContract _rootLibrary;
late final IsolateMirrorContract _isolate;
late final TypeMirrorContract _dynamicType;
late final TypeMirrorContract _voidType;
late final TypeMirrorContract _neverType;
// Private constructor
MirrorSystem._() {
_initializeSystem();
}
void _initializeSystem() {
_initializeRootLibrary();
_initializeCoreDependencies();
_initializeSpecialTypes();
_initializeIsolate();
}
void _initializeRootLibrary() {
_rootLibrary = LibraryMirror.withDeclarations(
name: 'dart.core',
uri: Uri.parse('dart:core'),
);
_libraries[_rootLibrary.uri] = _rootLibrary;
}
void _initializeCoreDependencies() {
// Create core library mirror
final coreLibrary = LibraryMirror.withDeclarations(
name: 'dart:core',
uri: _createDartUri('core'),
owner: null,
);
// Create async library mirror
final asyncLibrary = LibraryMirror.withDeclarations(
name: 'dart:async',
uri: _createDartUri('async'),
owner: null,
);
// Create test library mirror
final testLibrary = LibraryMirror.withDeclarations(
name: 'package:test/test.dart',
uri: Uri.parse('package:test/test.dart'),
owner: null,
);
// Add dependencies to core library
final coreDependencies = [
LibraryDependencyMirror(
isImport: true,
isDeferred: false,
sourceLibrary: coreLibrary,
targetLibrary: asyncLibrary,
prefix: null,
combinators: const [],
),
LibraryDependencyMirror(
isImport: false,
isDeferred: false,
sourceLibrary: coreLibrary,
targetLibrary: asyncLibrary,
prefix: null,
combinators: const [],
),
];
// Update core library with dependencies
_libraries[coreLibrary.uri] = LibraryMirror(
name: 'dart:core',
uri: _createDartUri('core'),
owner: null,
declarations: const {},
libraryDependencies: coreDependencies,
metadata: [],
);
// Add libraries to the map
_libraries[asyncLibrary.uri] = asyncLibrary;
_libraries[testLibrary.uri] = testLibrary;
}
void _initializeSpecialTypes() {
_dynamicType = TypeMirror.dynamicType();
_voidType = TypeMirror.voidType();
_neverType = TypeMirror(
type: Never,
name: 'Never',
owner: null,
metadata: [],
);
}
void _initializeIsolate() {
_isolate = IsolateMirror.current(_rootLibrary);
}
/// Creates a URI for a dart: library.
static Uri _createDartUri(String library) {
return Uri(scheme: 'dart', path: library);
}
/// Parses a library name into a URI.
static Uri _parseLibraryName(String name) {
if (name.startsWith('"') && name.endsWith('"')) {
name = name.substring(1, name.length - 1);
}
if (name.startsWith('dart:')) {
final library = name.substring(5);
return _createDartUri(library);
}
return Uri.parse(name);
}
@override
Map<Uri, LibraryMirrorContract> get libraries => Map.unmodifiable(_libraries);
@override
LibraryMirrorContract findLibrary(Symbol libraryName) {
final name = libraryName.toString();
// Remove leading 'Symbol(' and trailing ')'
final normalizedName = name.substring(7, name.length - 1);
final uri = _parseLibraryName(normalizedName);
final library = _libraries[uri];
if (library == null) {
throw ArgumentError('Library not found: $normalizedName');
}
return library;
}
@override
ClassMirrorContract reflectClass(Type type) {
return _classes.putIfAbsent(
type,
() => _createClassMirror(type),
);
}
ClassMirrorContract _createClassMirror(Type type) {
// Check if type is reflectable
if (!Reflector.isReflectable(type)) {
throw ArgumentError('Type is not reflectable: $type');
}
// Create temporary class mirror to serve as owner
final tempMirror = ClassMirror(
type: type,
name: type.toString(),
owner: null,
declarations: const {},
instanceMembers: const {},
staticMembers: const {},
metadata: [],
);
// Get metadata from registry
final properties = Reflector.getPropertyMetadata(type) ?? {};
final methods = Reflector.getMethodMetadata(type) ?? {};
// Create declarations map
final declarations = <Symbol, DeclarationMirrorContract>{};
final instanceMembers = <Symbol, MethodMirrorContract>{};
final staticMembers = <Symbol, MethodMirrorContract>{};
// Add properties and methods to declarations
properties.forEach((name, prop) {
declarations[Symbol(name)] = VariableMirror(
name: name,
type: TypeMirror(
type: prop.type,
name: prop.type.toString(),
owner: tempMirror,
metadata: [],
),
owner: tempMirror,
isStatic: false,
isFinal: !prop.isWritable,
isConst: false,
metadata: [],
);
});
methods.forEach((name, method) {
final methodMirror = MethodMirror(
name: name,
owner: tempMirror,
returnType: method.returnsVoid
? TypeMirror.voidType(tempMirror)
: TypeMirror.dynamicType(tempMirror),
parameters: method.parameters
.map((param) => ParameterMirror(
name: param.name,
type: TypeMirror(
type: param.type,
name: param.type.toString(),
owner: tempMirror,
metadata: [],
),
owner: tempMirror,
isOptional: !param.isRequired,
isNamed: param.isNamed,
metadata: [],
))
.toList(),
isStatic: method.isStatic,
metadata: [],
);
declarations[Symbol(name)] = methodMirror;
if (method.isStatic) {
staticMembers[Symbol(name)] = methodMirror;
} else {
instanceMembers[Symbol(name)] = methodMirror;
}
});
// Create class mirror
final mirror = ClassMirror(
type: type,
name: type.toString(),
owner: null,
declarations: declarations,
instanceMembers: instanceMembers,
staticMembers: staticMembers,
metadata: [],
);
// Update owners to point to the real class mirror
declarations.forEach((_, decl) {
if (decl is MutableOwnerMirror) {
decl.setOwner(mirror);
}
});
return mirror;
}
@override
TypeMirrorContract reflectType(Type type) {
return _getOrCreateTypeMirror(type);
}
TypeMirrorContract _getOrCreateTypeMirror(Type type) {
return _types.putIfAbsent(
type,
() => TypeMirror(
type: type,
name: type.toString(),
owner: _rootLibrary,
metadata: const [],
),
);
}
@override
IsolateMirrorContract get isolate => _isolate;
@override
TypeMirrorContract get dynamicType => _dynamicType;
@override
TypeMirrorContract get voidType => _voidType;
@override
TypeMirrorContract get neverType => _neverType;
/// Adds a library to the mirror system.
void addLibrary(LibraryMirrorContract library) {
_libraries[library.uri] = library;
}
/// Removes a library from the mirror system.
void removeLibrary(Uri uri) {
_libraries.remove(uri);
}
/// Creates a mirror reflecting [reflectee].
InstanceMirrorContract reflect(Object reflectee) {
return InstanceMirror(
reflectee: reflectee,
type: reflectClass(reflectee.runtimeType),
);
}
}
/// The current mirror system.
MirrorSystemContract currentMirrorSystem() => MirrorSystem.current();
/// Reflects an instance.
InstanceMirrorContract reflect(Object reflectee) =>
MirrorSystem.instance.reflect(reflectee);
/// Reflects a class.
ClassMirrorContract reflectClass(Type key) =>
MirrorSystem.instance.reflectClass(key);
/// Reflects a type.
TypeMirrorContract reflectType(Type key) =>
MirrorSystem.instance.reflectType(key);

View file

@ -1,15 +0,0 @@
/// Mirror implementations for the reflection system.
library mirrors;
export 'base_mirror.dart';
export 'class_mirror_impl.dart';
export 'combinator_mirror_impl.dart';
export 'instance_mirror_impl.dart';
export 'isolate_mirror_impl.dart';
export 'library_dependency_mirror_impl.dart';
export 'library_mirror_impl.dart';
export 'method_mirror_impl.dart';
export 'parameter_mirror_impl.dart';
export 'special_types.dart';
export 'type_mirror_impl.dart';
export 'variable_mirror_impl.dart';

View file

@ -1,32 +1,31 @@
import 'dart:core'; import 'dart:core';
import '../mirrors.dart'; import 'package:platform_contracts/contracts.dart';
import 'base_mirror.dart'; import 'package:platform_reflection/mirrors.dart';
import 'type_mirror_impl.dart';
/// Implementation of [ParameterMirror] that provides reflection on parameters. /// Implementation of [ParameterMirrorContract] that provides reflection on parameters.
class ParameterMirrorImpl extends MutableOwnerMirror class ParameterMirror extends MutableOwnerMirror
implements ParameterMirror { implements ParameterMirrorContract {
final String _name; final String _name;
final TypeMirror _type; final TypeMirrorContract _type;
final bool _isOptional; final bool _isOptional;
final bool _isNamed; final bool _isNamed;
final bool _hasDefaultValue; final bool _hasDefaultValue;
final InstanceMirror? _defaultValue; final InstanceMirrorContract? _defaultValue;
final bool _isFinal; final bool _isFinal;
final bool _isConst; final bool _isConst;
final List<InstanceMirror> _metadata; final List<InstanceMirrorContract> _metadata;
ParameterMirrorImpl({ ParameterMirror({
required String name, required String name,
required TypeMirror type, required TypeMirrorContract type,
required DeclarationMirror owner, required DeclarationMirrorContract owner,
bool isOptional = false, bool isOptional = false,
bool isNamed = false, bool isNamed = false,
bool hasDefaultValue = false, bool hasDefaultValue = false,
InstanceMirror? defaultValue, InstanceMirrorContract? defaultValue,
bool isFinal = false, bool isFinal = false,
bool isConst = false, bool isConst = false,
List<InstanceMirror> metadata = const [], List<InstanceMirrorContract> metadata = const [],
}) : _name = name, }) : _name = name,
_type = type, _type = type,
_isOptional = isOptional, _isOptional = isOptional,
@ -58,7 +57,7 @@ class ParameterMirrorImpl extends MutableOwnerMirror
bool get isTopLevel => false; bool get isTopLevel => false;
@override @override
TypeMirror get type => _type; TypeMirrorContract get type => _type;
@override @override
bool get isStatic => false; bool get isStatic => false;
@ -79,15 +78,15 @@ class ParameterMirrorImpl extends MutableOwnerMirror
bool get hasDefaultValue => _hasDefaultValue; bool get hasDefaultValue => _hasDefaultValue;
@override @override
InstanceMirror? get defaultValue => _defaultValue; InstanceMirrorContract? get defaultValue => _defaultValue;
@override @override
List<InstanceMirror> get metadata => List.unmodifiable(_metadata); List<InstanceMirrorContract> get metadata => List.unmodifiable(_metadata);
@override @override
bool operator ==(Object other) { bool operator ==(Object other) {
if (identical(this, other)) return true; if (identical(this, other)) return true;
if (other is! ParameterMirrorImpl) return false; if (other is! ParameterMirror) return false;
return _name == other._name && return _name == other._name &&
_type == other._type && _type == other._type &&

View file

@ -1,33 +1,23 @@
import 'dart:core'; import 'dart:core';
import '../mirrors.dart'; import 'package:platform_contracts/contracts.dart';
import '../core/reflector.dart'; import 'package:platform_reflection/mirrors.dart';
import 'type_mirror_impl.dart';
import 'class_mirror_impl.dart';
import 'library_mirror_impl.dart';
import 'library_dependency_mirror_impl.dart';
import 'isolate_mirror_impl.dart';
import 'special_types.dart';
import 'variable_mirror_impl.dart';
import 'method_mirror_impl.dart';
import 'parameter_mirror_impl.dart';
import 'base_mirror.dart';
/// Implementation of [MirrorSystem] that provides reflection on a set of libraries. /// Implementation of [MirrorSystemContract] that provides reflection on a set of libraries.
class MirrorSystemImpl implements MirrorSystem { class MirrorSystem implements MirrorSystemContract {
final Map<Uri, LibraryMirror> _libraries; final Map<Uri, LibraryMirrorContract> _libraries;
final IsolateMirror _isolate; final IsolateMirrorContract _isolate;
final TypeMirror _dynamicType; final TypeMirrorContract _dynamicType;
final TypeMirror _voidType; final TypeMirrorContract _voidType;
final TypeMirror _neverType; final TypeMirrorContract _neverType;
MirrorSystemImpl({ MirrorSystem({
required Map<Uri, LibraryMirror> libraries, required Map<Uri, LibraryMirrorContract> libraries,
required IsolateMirror isolate, required IsolateMirrorContract isolate,
}) : _libraries = libraries, }) : _libraries = libraries,
_isolate = isolate, _isolate = isolate,
_dynamicType = TypeMirrorImpl.dynamicType(), _dynamicType = TypeMirror.dynamicType(),
_voidType = TypeMirrorImpl.voidType(), _voidType = TypeMirror.voidType(),
_neverType = TypeMirrorImpl( _neverType = TypeMirror(
type: Never, type: Never,
name: 'Never', name: 'Never',
owner: null, owner: null,
@ -35,23 +25,23 @@ class MirrorSystemImpl implements MirrorSystem {
); );
/// Creates a mirror system for the current isolate. /// Creates a mirror system for the current isolate.
factory MirrorSystemImpl.current() { factory MirrorSystem.current() {
// Create core library mirror // Create core library mirror
final coreLibrary = LibraryMirrorImpl.withDeclarations( final coreLibrary = LibraryMirror.withDeclarations(
name: 'dart:core', name: 'dart:core',
uri: _createDartUri('core'), uri: _createDartUri('core'),
owner: null, owner: null,
); );
// Create async library mirror // Create async library mirror
final asyncLibrary = LibraryMirrorImpl.withDeclarations( final asyncLibrary = LibraryMirror.withDeclarations(
name: 'dart:async', name: 'dart:async',
uri: _createDartUri('async'), uri: _createDartUri('async'),
owner: null, owner: null,
); );
// Create test library mirror // Create test library mirror
final testLibrary = LibraryMirrorImpl.withDeclarations( final testLibrary = LibraryMirror.withDeclarations(
name: 'package:test/test.dart', name: 'package:test/test.dart',
uri: Uri.parse('package:test/test.dart'), uri: Uri.parse('package:test/test.dart'),
owner: null, owner: null,
@ -59,7 +49,7 @@ class MirrorSystemImpl implements MirrorSystem {
// Add dependencies to core library // Add dependencies to core library
final coreDependencies = [ final coreDependencies = [
LibraryDependencyMirrorImpl( LibraryDependencyMirror(
isImport: true, isImport: true,
isDeferred: false, isDeferred: false,
sourceLibrary: coreLibrary, sourceLibrary: coreLibrary,
@ -67,7 +57,7 @@ class MirrorSystemImpl implements MirrorSystem {
prefix: null, prefix: null,
combinators: const [], combinators: const [],
), ),
LibraryDependencyMirrorImpl( LibraryDependencyMirror(
isImport: false, isImport: false,
isDeferred: false, isDeferred: false,
sourceLibrary: coreLibrary, sourceLibrary: coreLibrary,
@ -78,7 +68,7 @@ class MirrorSystemImpl implements MirrorSystem {
]; ];
// Create root library with dependencies // Create root library with dependencies
final rootLibrary = LibraryMirrorImpl( final rootLibrary = LibraryMirror(
name: 'dart:core', name: 'dart:core',
uri: _createDartUri('core'), uri: _createDartUri('core'),
owner: null, owner: null,
@ -88,16 +78,16 @@ class MirrorSystemImpl implements MirrorSystem {
); );
// Create isolate mirror // Create isolate mirror
final isolate = IsolateMirrorImpl.current(rootLibrary); final isolate = IsolateMirror.current(rootLibrary);
// Create initial libraries map // Create initial libraries map
final libraries = <Uri, LibraryMirror>{ final libraries = <Uri, LibraryMirrorContract>{
rootLibrary.uri: rootLibrary, rootLibrary.uri: rootLibrary,
asyncLibrary.uri: asyncLibrary, asyncLibrary.uri: asyncLibrary,
testLibrary.uri: testLibrary, testLibrary.uri: testLibrary,
}; };
return MirrorSystemImpl( return MirrorSystem(
libraries: libraries, libraries: libraries,
isolate: isolate, isolate: isolate,
); );
@ -123,10 +113,10 @@ class MirrorSystemImpl implements MirrorSystem {
} }
@override @override
Map<Uri, LibraryMirror> get libraries => Map.unmodifiable(_libraries); Map<Uri, LibraryMirrorContract> get libraries => Map.unmodifiable(_libraries);
@override @override
LibraryMirror findLibrary(Symbol libraryName) { LibraryMirrorContract findLibrary(Symbol libraryName) {
final name = libraryName.toString(); final name = libraryName.toString();
// Remove leading 'Symbol(' and trailing ')' // Remove leading 'Symbol(' and trailing ')'
final normalizedName = name.substring(7, name.length - 1); final normalizedName = name.substring(7, name.length - 1);
@ -140,14 +130,14 @@ class MirrorSystemImpl implements MirrorSystem {
} }
@override @override
ClassMirror reflectClass(Type type) { ClassMirrorContract reflectClass(Type type) {
// Check if type is reflectable // Check if type is reflectable
if (!Reflector.isReflectable(type)) { if (!Reflector.isReflectable(type)) {
throw ArgumentError('Type is not reflectable: $type'); throw ArgumentError('Type is not reflectable: $type');
} }
// Create temporary class mirror to serve as owner // Create temporary class mirror to serve as owner
final tempMirror = ClassMirrorImpl( final tempMirror = ClassMirror(
type: type, type: type,
name: type.toString(), name: type.toString(),
owner: null, owner: null,
@ -160,18 +150,18 @@ class MirrorSystemImpl implements MirrorSystem {
// Get metadata from registry // Get metadata from registry
final properties = Reflector.getPropertyMetadata(type) ?? {}; final properties = Reflector.getPropertyMetadata(type) ?? {};
final methods = Reflector.getMethodMetadata(type) ?? {}; final methods = Reflector.getMethodMetadata(type) ?? {};
final constructors = Reflector.getConstructorMetadata(type) ?? []; //final constructors = Reflector.getConstructorMetadata(type) ?? [];
// Create declarations map // Create declarations map
final declarations = <Symbol, DeclarationMirror>{}; final declarations = <Symbol, DeclarationMirrorContract>{};
final instanceMembers = <Symbol, MethodMirror>{}; final instanceMembers = <Symbol, MethodMirrorContract>{};
final staticMembers = <Symbol, MethodMirror>{}; final staticMembers = <Symbol, MethodMirrorContract>{};
// Add properties and methods to declarations // Add properties and methods to declarations
properties.forEach((name, prop) { properties.forEach((name, prop) {
declarations[Symbol(name)] = VariableMirrorImpl( declarations[Symbol(name)] = VariableMirror(
name: name, name: name,
type: TypeMirrorImpl( type: TypeMirror(
type: prop.type, type: prop.type,
name: prop.type.toString(), name: prop.type.toString(),
owner: tempMirror, owner: tempMirror,
@ -186,16 +176,16 @@ class MirrorSystemImpl implements MirrorSystem {
}); });
methods.forEach((name, method) { methods.forEach((name, method) {
final methodMirror = MethodMirrorImpl( final methodMirror = MethodMirror(
name: name, name: name,
owner: tempMirror, owner: tempMirror,
returnType: method.returnsVoid returnType: method.returnsVoid
? TypeMirrorImpl.voidType(tempMirror) ? TypeMirror.voidType(tempMirror)
: TypeMirrorImpl.dynamicType(tempMirror), : TypeMirror.dynamicType(tempMirror),
parameters: method.parameters parameters: method.parameters
.map((param) => ParameterMirrorImpl( .map((param) => ParameterMirror(
name: param.name, name: param.name,
type: TypeMirrorImpl( type: TypeMirror(
type: param.type, type: param.type,
name: param.type.toString(), name: param.type.toString(),
owner: tempMirror, owner: tempMirror,
@ -220,7 +210,7 @@ class MirrorSystemImpl implements MirrorSystem {
}); });
// Create class mirror // Create class mirror
final mirror = ClassMirrorImpl( final mirror = ClassMirror(
type: type, type: type,
name: type.toString(), name: type.toString(),
owner: null, owner: null,
@ -241,13 +231,13 @@ class MirrorSystemImpl implements MirrorSystem {
} }
@override @override
TypeMirror reflectType(Type type) { TypeMirrorContract reflectType(Type type) {
// Check if type is reflectable // Check if type is reflectable
if (!Reflector.isReflectable(type)) { if (!Reflector.isReflectable(type)) {
throw ArgumentError('Type is not reflectable: $type'); throw ArgumentError('Type is not reflectable: $type');
} }
return TypeMirrorImpl( return TypeMirror(
type: type, type: type,
name: type.toString(), name: type.toString(),
owner: null, owner: null,
@ -256,19 +246,19 @@ class MirrorSystemImpl implements MirrorSystem {
} }
@override @override
IsolateMirror get isolate => _isolate; IsolateMirrorContract get isolate => _isolate;
@override @override
TypeMirror get dynamicType => _dynamicType; TypeMirrorContract get dynamicType => _dynamicType;
@override @override
TypeMirror get voidType => _voidType; TypeMirrorContract get voidType => _voidType;
@override @override
TypeMirror get neverType => _neverType; TypeMirrorContract get neverType => _neverType;
/// Adds a library to the mirror system. /// Adds a library to the mirror system.
void addLibrary(LibraryMirror library) { void addLibrary(LibraryMirrorContract library) {
_libraries[library.uri] = library; _libraries[library.uri] = library;
} }

View file

@ -0,0 +1,315 @@
import 'dart:core';
import 'package:platform_contracts/contracts.dart';
import 'package:platform_reflection/mirrors.dart';
/// Implementation of [MirrorSystemContract] that provides reflection on a set of libraries.
class MirrorSystem implements MirrorSystemContract {
/// The singleton instance of the mirror system.
static final instance = MirrorSystem._();
final Map<Uri, LibraryMirrorContract> _libraries;
final Map<Type, ClassMirrorContract> _classes = {};
final Map<Type, TypeMirrorContract> _types = {};
late final LibraryMirrorContract _rootLibrary;
late final IsolateMirrorContract _isolate;
late final TypeMirrorContract _dynamicType;
late final TypeMirrorContract _voidType;
late final TypeMirrorContract _neverType;
MirrorSystem._() : _libraries = {} {
_initializeSystem();
}
void _initializeSystem() {
_initializeRootLibrary();
_initializeCoreDependencies();
_initializeSpecialTypes();
_initializeIsolate();
}
void _initializeRootLibrary() {
_rootLibrary = LibraryMirror.withDeclarations(
name: 'dart.core',
uri: Uri.parse('dart:core'),
);
_libraries[_rootLibrary.uri] = _rootLibrary;
}
void _initializeCoreDependencies() {
// Create core library mirror
final coreLibrary = LibraryMirror.withDeclarations(
name: 'dart:core',
uri: _createDartUri('core'),
owner: null,
);
// Create async library mirror
final asyncLibrary = LibraryMirror.withDeclarations(
name: 'dart:async',
uri: _createDartUri('async'),
owner: null,
);
// Create test library mirror
final testLibrary = LibraryMirror.withDeclarations(
name: 'package:test/test.dart',
uri: Uri.parse('package:test/test.dart'),
owner: null,
);
// Add dependencies to core library
final coreDependencies = [
LibraryDependencyMirror(
isImport: true,
isDeferred: false,
sourceLibrary: coreLibrary,
targetLibrary: asyncLibrary,
prefix: null,
combinators: const [],
),
LibraryDependencyMirror(
isImport: false,
isDeferred: false,
sourceLibrary: coreLibrary,
targetLibrary: asyncLibrary,
prefix: null,
combinators: const [],
),
];
// Update root library with dependencies
_rootLibrary = LibraryMirror(
name: 'dart:core',
uri: _createDartUri('core'),
owner: null,
declarations: const {},
libraryDependencies: coreDependencies,
metadata: [],
);
// Add libraries to the map
_libraries[coreLibrary.uri] = coreLibrary;
_libraries[asyncLibrary.uri] = asyncLibrary;
_libraries[testLibrary.uri] = testLibrary;
}
void _initializeSpecialTypes() {
_dynamicType = TypeMirror.dynamicType();
_voidType = TypeMirror.voidType();
_neverType = TypeMirror(
type: Never,
name: 'Never',
owner: null,
metadata: [],
);
}
void _initializeIsolate() {
_isolate = IsolateMirror.current(_rootLibrary);
}
/// Creates a URI for a dart: library.
static Uri _createDartUri(String library) {
return Uri(scheme: 'dart', path: library);
}
/// Parses a library name into a URI.
static Uri _parseLibraryName(String name) {
if (name.startsWith('"') && name.endsWith('"')) {
name = name.substring(1, name.length - 1);
}
if (name.startsWith('dart:')) {
final library = name.substring(5);
return _createDartUri(library);
}
return Uri.parse(name);
}
@override
Map<Uri, LibraryMirrorContract> get libraries => Map.unmodifiable(_libraries);
@override
LibraryMirrorContract findLibrary(Symbol libraryName) {
final name = libraryName.toString();
// Remove leading 'Symbol(' and trailing ')'
final normalizedName = name.substring(7, name.length - 1);
final uri = _parseLibraryName(normalizedName);
final library = _libraries[uri];
if (library == null) {
throw ArgumentError('Library not found: $normalizedName');
}
return library;
}
@override
ClassMirrorContract reflectClass(Type type) {
return _classes.putIfAbsent(
type,
() => _createClassMirror(type),
);
}
ClassMirrorContract _createClassMirror(Type type) {
// Check if type is reflectable
if (!Reflector.isReflectable(type)) {
throw ArgumentError('Type is not reflectable: $type');
}
// Create temporary class mirror to serve as owner
final tempMirror = ClassMirror(
type: type,
name: type.toString(),
owner: null,
declarations: const {},
instanceMembers: const {},
staticMembers: const {},
metadata: [],
);
// Get metadata from registry
final properties = Reflector.getPropertyMetadata(type) ?? {};
final methods = Reflector.getMethodMetadata(type) ?? {};
// Create declarations map
final declarations = <Symbol, DeclarationMirrorContract>{};
final instanceMembers = <Symbol, MethodMirrorContract>{};
final staticMembers = <Symbol, MethodMirrorContract>{};
// Add properties and methods to declarations
properties.forEach((name, prop) {
declarations[Symbol(name)] = VariableMirror(
name: name,
type: TypeMirror(
type: prop.type,
name: prop.type.toString(),
owner: tempMirror,
metadata: [],
),
owner: tempMirror,
isStatic: false,
isFinal: !prop.isWritable,
isConst: false,
metadata: [],
);
});
methods.forEach((name, method) {
final methodMirror = MethodMirror(
name: name,
owner: tempMirror,
returnType: method.returnsVoid
? TypeMirror.voidType(tempMirror)
: TypeMirror.dynamicType(tempMirror),
parameters: method.parameters
.map((param) => ParameterMirror(
name: param.name,
type: TypeMirror(
type: param.type,
name: param.type.toString(),
owner: tempMirror,
metadata: [],
),
owner: tempMirror,
isOptional: !param.isRequired,
isNamed: param.isNamed,
metadata: [],
))
.toList(),
isStatic: method.isStatic,
metadata: [],
);
declarations[Symbol(name)] = methodMirror;
if (method.isStatic) {
staticMembers[Symbol(name)] = methodMirror;
} else {
instanceMembers[Symbol(name)] = methodMirror;
}
});
// Create class mirror
final mirror = ClassMirror(
type: type,
name: type.toString(),
owner: null,
declarations: declarations,
instanceMembers: instanceMembers,
staticMembers: staticMembers,
metadata: [],
);
// Update owners to point to the real class mirror
declarations.forEach((_, decl) {
if (decl is MutableOwnerMirror) {
decl.setOwner(mirror);
}
});
return mirror;
}
@override
TypeMirrorContract reflectType(Type type) {
return _getOrCreateTypeMirror(type);
}
TypeMirrorContract _getOrCreateTypeMirror(Type type) {
return _types.putIfAbsent(
type,
() => TypeMirror(
type: type,
name: type.toString(),
owner: _rootLibrary,
metadata: const [],
),
);
}
@override
IsolateMirrorContract get isolate => _isolate;
@override
TypeMirrorContract get dynamicType => _dynamicType;
@override
TypeMirrorContract get voidType => _voidType;
@override
TypeMirrorContract get neverType => _neverType;
/// Adds a library to the mirror system.
void addLibrary(LibraryMirrorContract library) {
_libraries[library.uri] = library;
}
/// Removes a library from the mirror system.
void removeLibrary(Uri uri) {
_libraries.remove(uri);
}
/// Creates a mirror reflecting [reflectee].
InstanceMirrorContract reflect(Object reflectee) {
return InstanceMirror(
reflectee: reflectee,
type: reflectClass(reflectee.runtimeType),
);
}
}
/// The current mirror system.
MirrorSystemContract currentMirrorSystem() => MirrorSystem.instance;
/// Reflects an instance.
InstanceMirrorContract reflect(Object reflectee) =>
MirrorSystem.instance.reflect(reflectee);
/// Reflects a class.
ClassMirrorContract reflectClass(Type key) =>
MirrorSystem.instance.reflectClass(key);
/// Reflects a type.
TypeMirrorContract reflectType(Type key) =>
MirrorSystem.instance.reflectType(key);

View file

@ -0,0 +1,318 @@
import 'dart:core';
import 'package:platform_contracts/contracts.dart';
import 'package:platform_reflection/mirrors.dart';
/// Implementation of [MirrorSystemContract] that provides reflection on a set of libraries.
class MirrorSystem implements MirrorSystemContract {
static MirrorSystem? _instance;
static MirrorSystem get instance {
return _instance ??= MirrorSystem._();
}
final Map<Uri, LibraryMirrorContract> _libraries = {};
final Map<Type, ClassMirrorContract> _classes = {};
final Map<Type, TypeMirrorContract> _types = {};
late final LibraryMirrorContract _rootLibrary;
late final IsolateMirrorContract _isolate;
late final TypeMirrorContract _dynamicType;
late final TypeMirrorContract _voidType;
late final TypeMirrorContract _neverType;
// Private constructor
MirrorSystem._() {
_initializeSystem();
}
void _initializeSystem() {
_initializeRootLibrary();
_initializeCoreDependencies();
_initializeSpecialTypes();
_initializeIsolate();
}
void _initializeRootLibrary() {
_rootLibrary = LibraryMirror.withDeclarations(
name: 'dart.core',
uri: Uri.parse('dart:core'),
);
_libraries[_rootLibrary.uri] = _rootLibrary;
}
void _initializeCoreDependencies() {
// Create core library mirror
final coreLibrary = LibraryMirror.withDeclarations(
name: 'dart:core',
uri: _createDartUri('core'),
owner: null,
);
// Create async library mirror
final asyncLibrary = LibraryMirror.withDeclarations(
name: 'dart:async',
uri: _createDartUri('async'),
owner: null,
);
// Create test library mirror
final testLibrary = LibraryMirror.withDeclarations(
name: 'package:test/test.dart',
uri: Uri.parse('package:test/test.dart'),
owner: null,
);
// Add dependencies to core library
final coreDependencies = [
LibraryDependencyMirror(
isImport: true,
isDeferred: false,
sourceLibrary: coreLibrary,
targetLibrary: asyncLibrary,
prefix: null,
combinators: const [],
),
LibraryDependencyMirror(
isImport: false,
isDeferred: false,
sourceLibrary: coreLibrary,
targetLibrary: asyncLibrary,
prefix: null,
combinators: const [],
),
];
// Update core library with dependencies
_libraries[coreLibrary.uri] = LibraryMirror(
name: 'dart:core',
uri: _createDartUri('core'),
owner: null,
declarations: const {},
libraryDependencies: coreDependencies,
metadata: [],
);
// Add libraries to the map
_libraries[asyncLibrary.uri] = asyncLibrary;
_libraries[testLibrary.uri] = testLibrary;
}
void _initializeSpecialTypes() {
_dynamicType = TypeMirror.dynamicType();
_voidType = TypeMirror.voidType();
_neverType = TypeMirror(
type: Never,
name: 'Never',
owner: null,
metadata: [],
);
}
void _initializeIsolate() {
_isolate = IsolateMirror.current(_rootLibrary);
}
/// Creates a URI for a dart: library.
static Uri _createDartUri(String library) {
return Uri(scheme: 'dart', path: library);
}
/// Parses a library name into a URI.
static Uri _parseLibraryName(String name) {
if (name.startsWith('"') && name.endsWith('"')) {
name = name.substring(1, name.length - 1);
}
if (name.startsWith('dart:')) {
final library = name.substring(5);
return _createDartUri(library);
}
return Uri.parse(name);
}
@override
Map<Uri, LibraryMirrorContract> get libraries => Map.unmodifiable(_libraries);
@override
LibraryMirrorContract findLibrary(Symbol libraryName) {
final name = libraryName.toString();
// Remove leading 'Symbol(' and trailing ')'
final normalizedName = name.substring(7, name.length - 1);
final uri = _parseLibraryName(normalizedName);
final library = _libraries[uri];
if (library == null) {
throw ArgumentError('Library not found: $normalizedName');
}
return library;
}
@override
ClassMirrorContract reflectClass(Type type) {
return _classes.putIfAbsent(
type,
() => _createClassMirror(type),
);
}
ClassMirrorContract _createClassMirror(Type type) {
// Check if type is reflectable
if (!Reflector.isReflectable(type)) {
throw ArgumentError('Type is not reflectable: $type');
}
// Create temporary class mirror to serve as owner
final tempMirror = ClassMirror(
type: type,
name: type.toString(),
owner: null,
declarations: const {},
instanceMembers: const {},
staticMembers: const {},
metadata: [],
);
// Get metadata from registry
final properties = Reflector.getPropertyMetadata(type) ?? {};
final methods = Reflector.getMethodMetadata(type) ?? {};
// Create declarations map
final declarations = <Symbol, DeclarationMirrorContract>{};
final instanceMembers = <Symbol, MethodMirrorContract>{};
final staticMembers = <Symbol, MethodMirrorContract>{};
// Add properties and methods to declarations
properties.forEach((name, prop) {
declarations[Symbol(name)] = VariableMirror(
name: name,
type: TypeMirror(
type: prop.type,
name: prop.type.toString(),
owner: tempMirror,
metadata: [],
),
owner: tempMirror,
isStatic: false,
isFinal: !prop.isWritable,
isConst: false,
metadata: [],
);
});
methods.forEach((name, method) {
final methodMirror = MethodMirror(
name: name,
owner: tempMirror,
returnType: method.returnsVoid
? TypeMirror.voidType(tempMirror)
: TypeMirror.dynamicType(tempMirror),
parameters: method.parameters
.map((param) => ParameterMirror(
name: param.name,
type: TypeMirror(
type: param.type,
name: param.type.toString(),
owner: tempMirror,
metadata: [],
),
owner: tempMirror,
isOptional: !param.isRequired,
isNamed: param.isNamed,
metadata: [],
))
.toList(),
isStatic: method.isStatic,
metadata: [],
);
declarations[Symbol(name)] = methodMirror;
if (method.isStatic) {
staticMembers[Symbol(name)] = methodMirror;
} else {
instanceMembers[Symbol(name)] = methodMirror;
}
});
// Create class mirror
final mirror = ClassMirror(
type: type,
name: type.toString(),
owner: null,
declarations: declarations,
instanceMembers: instanceMembers,
staticMembers: staticMembers,
metadata: [],
);
// Update owners to point to the real class mirror
declarations.forEach((_, decl) {
if (decl is MutableOwnerMirror) {
decl.setOwner(mirror);
}
});
return mirror;
}
@override
TypeMirrorContract reflectType(Type type) {
return _getOrCreateTypeMirror(type);
}
TypeMirrorContract _getOrCreateTypeMirror(Type type) {
return _types.putIfAbsent(
type,
() => TypeMirror(
type: type,
name: type.toString(),
owner: _rootLibrary,
metadata: const [],
),
);
}
@override
IsolateMirrorContract get isolate => _isolate;
@override
TypeMirrorContract get dynamicType => _dynamicType;
@override
TypeMirrorContract get voidType => _voidType;
@override
TypeMirrorContract get neverType => _neverType;
/// Adds a library to the mirror system.
void addLibrary(LibraryMirrorContract library) {
_libraries[library.uri] = library;
}
/// Removes a library from the mirror system.
void removeLibrary(Uri uri) {
_libraries.remove(uri);
}
/// Creates a mirror reflecting [reflectee].
InstanceMirrorContract reflect(Object reflectee) {
return InstanceMirror(
reflectee: reflectee,
type: reflectClass(reflectee.runtimeType),
);
}
}
/// The current mirror system.
MirrorSystemContract currentMirrorSystem() => MirrorSystem.instance;
/// Reflects an instance.
InstanceMirrorContract reflect(Object reflectee) =>
MirrorSystem.instance.reflect(reflectee);
/// Reflects a class.
ClassMirrorContract reflectClass(Type key) =>
MirrorSystem.instance.reflectClass(key);
/// Reflects a type.
TypeMirrorContract reflectType(Type key) =>
MirrorSystem.instance.reflectType(key);

View file

@ -1,28 +1,25 @@
import 'dart:core'; import 'dart:core';
import '../mirrors.dart'; import 'package:platform_contracts/contracts.dart'
import '../core/reflector.dart'; hide PropertyMetadata, MethodMetadata, ConstructorMetadata;
import '../metadata.dart'; import 'package:platform_reflection/mirrors.dart';
import 'base_mirror.dart';
import 'special_types.dart';
import 'type_variable_mirror_impl.dart';
/// Implementation of [TypeMirror] that provides reflection on types. /// Implementation of [TypeMirrorContract] that provides reflection on types.
class TypeMirrorImpl extends TypedMirror implements TypeMirror { class TypeMirror extends TypedMirror implements TypeMirrorContract {
final List<TypeVariableMirror> _typeVariables; final List<TypeVariableMirrorContract> _typeVariables;
final List<TypeMirror> _typeArguments; final List<TypeMirrorContract> _typeArguments;
final bool _isOriginalDeclaration; final bool _isOriginalDeclaration;
final TypeMirror? _originalDeclaration; final TypeMirrorContract? _originalDeclaration;
final bool _isGeneric; final bool _isGeneric;
TypeMirrorImpl({ TypeMirror({
required Type type, required Type type,
required String name, required String name,
DeclarationMirror? owner, DeclarationMirrorContract? owner,
List<TypeVariableMirror> typeVariables = const [], List<TypeVariableMirrorContract> typeVariables = const [],
List<TypeMirror> typeArguments = const [], List<TypeMirrorContract> typeArguments = const [],
bool isOriginalDeclaration = true, bool isOriginalDeclaration = true,
TypeMirror? originalDeclaration, TypeMirrorContract? originalDeclaration,
List<InstanceMirror> metadata = const [], List<InstanceMirrorContract> metadata = const [],
}) : _typeVariables = typeVariables, }) : _typeVariables = typeVariables,
_typeArguments = typeArguments, _typeArguments = typeArguments,
_isOriginalDeclaration = isOriginalDeclaration, _isOriginalDeclaration = isOriginalDeclaration,
@ -46,19 +43,19 @@ class TypeMirrorImpl extends TypedMirror implements TypeMirror {
} }
/// Creates a TypeMirror from TypeMetadata. /// Creates a TypeMirror from TypeMetadata.
factory TypeMirrorImpl.fromMetadata(TypeMetadata typeMetadata, factory TypeMirror.fromMetadata(TypeMetadata typeMetadata,
[DeclarationMirror? owner]) { [DeclarationMirrorContract? owner]) {
// Get type variables from metadata // Get type variables from metadata
final typeVariables = typeMetadata.typeParameters.map((param) { final typeVariables = typeMetadata.typeParameters.map((param) {
// Create upper bound type mirror // Create upper bound type mirror
final upperBound = TypeMirrorImpl( final upperBound = TypeMirror(
type: param.bound ?? Object, type: param.bound ?? Object,
name: param.bound?.toString() ?? 'Object', name: param.bound?.toString() ?? 'Object',
owner: owner, owner: owner,
); );
// Create type variable mirror // Create type variable mirror
return TypeVariableMirrorImpl( return TypeVariableMirror(
type: param.type, type: param.type,
name: param.name, name: param.name,
upperBound: upperBound, upperBound: upperBound,
@ -68,14 +65,14 @@ class TypeMirrorImpl extends TypedMirror implements TypeMirror {
// Get type arguments from metadata // Get type arguments from metadata
final typeArguments = typeMetadata.typeArguments.map((arg) { final typeArguments = typeMetadata.typeArguments.map((arg) {
return TypeMirrorImpl( return TypeMirror(
type: arg.type, type: arg.type,
name: arg.name, name: arg.name,
owner: owner, owner: owner,
); );
}).toList(); }).toList();
return TypeMirrorImpl( return TypeMirror(
type: typeMetadata.type, type: typeMetadata.type,
name: typeMetadata.name, name: typeMetadata.name,
owner: owner, owner: owner,
@ -86,8 +83,8 @@ class TypeMirrorImpl extends TypedMirror implements TypeMirror {
} }
/// Creates a TypeMirror for void. /// Creates a TypeMirror for void.
factory TypeMirrorImpl.voidType([DeclarationMirror? owner]) { factory TypeMirror.voidType([DeclarationMirrorContract? owner]) {
return TypeMirrorImpl( return TypeMirror(
type: voidType, type: voidType,
name: 'void', name: 'void',
owner: owner, owner: owner,
@ -96,8 +93,8 @@ class TypeMirrorImpl extends TypedMirror implements TypeMirror {
} }
/// Creates a TypeMirror for dynamic. /// Creates a TypeMirror for dynamic.
factory TypeMirrorImpl.dynamicType([DeclarationMirror? owner]) { factory TypeMirror.dynamicType([DeclarationMirrorContract? owner]) {
return TypeMirrorImpl( return TypeMirror(
type: dynamicType, type: dynamicType,
name: 'dynamic', name: 'dynamic',
owner: owner, owner: owner,
@ -106,7 +103,8 @@ class TypeMirrorImpl extends TypedMirror implements TypeMirror {
} }
/// Creates a new TypeMirror with the given type arguments. /// Creates a new TypeMirror with the given type arguments.
TypeMirror instantiateGeneric(List<TypeMirror> typeArguments) { TypeMirrorContract instantiateGeneric(
List<TypeMirrorContract> typeArguments) {
if (!_isGeneric) { if (!_isGeneric) {
throw StateError('Type $name is not generic'); throw StateError('Type $name is not generic');
} }
@ -126,7 +124,7 @@ class TypeMirrorImpl extends TypedMirror implements TypeMirror {
} }
} }
return TypeMirrorImpl( return TypeMirror(
type: type, type: type,
name: name, name: name,
owner: owner, owner: owner,
@ -145,17 +143,18 @@ class TypeMirrorImpl extends TypedMirror implements TypeMirror {
Type get reflectedType => type; Type get reflectedType => type;
@override @override
List<TypeVariableMirror> get typeVariables => List<TypeVariableMirrorContract> get typeVariables =>
List.unmodifiable(_typeVariables); List.unmodifiable(_typeVariables);
@override @override
List<TypeMirror> get typeArguments => List.unmodifiable(_typeArguments); List<TypeMirrorContract> get typeArguments =>
List.unmodifiable(_typeArguments);
@override @override
bool get isOriginalDeclaration => _isOriginalDeclaration; bool get isOriginalDeclaration => _isOriginalDeclaration;
@override @override
TypeMirror get originalDeclaration { TypeMirrorContract get originalDeclaration {
if (isOriginalDeclaration) return this; if (isOriginalDeclaration) return this;
return _originalDeclaration!; return _originalDeclaration!;
} }
@ -176,9 +175,9 @@ class TypeMirrorImpl extends TypedMirror implements TypeMirror {
Reflector.getConstructorMetadata(type) ?? []; Reflector.getConstructorMetadata(type) ?? [];
@override @override
bool isSubtypeOf(TypeMirror other) { bool isSubtypeOf(TypeMirrorContract other) {
if (this == other) return true; if (this == other) return true;
if (other is! TypeMirrorImpl) return false; if (other is! TypeMirror) return false;
// Never is a subtype of all types // Never is a subtype of all types
if (type == Never) return true; if (type == Never) return true;
@ -195,19 +194,19 @@ class TypeMirrorImpl extends TypedMirror implements TypeMirror {
// Check supertype // Check supertype
if (metadata.supertype != null) { if (metadata.supertype != null) {
final superMirror = TypeMirrorImpl.fromMetadata(metadata.supertype!); final superMirror = TypeMirror.fromMetadata(metadata.supertype!);
if (superMirror.isSubtypeOf(other)) return true; if (superMirror.isSubtypeOf(other)) return true;
} }
// Check interfaces // Check interfaces
for (final interface in metadata.interfaces) { for (final interface in metadata.interfaces) {
final interfaceMirror = TypeMirrorImpl.fromMetadata(interface); final interfaceMirror = TypeMirror.fromMetadata(interface);
if (interfaceMirror.isSubtypeOf(other)) return true; if (interfaceMirror.isSubtypeOf(other)) return true;
} }
// Check mixins // Check mixins
for (final mixin in metadata.mixins) { for (final mixin in metadata.mixins) {
final mixinMirror = TypeMirrorImpl.fromMetadata(mixin); final mixinMirror = TypeMirror.fromMetadata(mixin);
if (mixinMirror.isSubtypeOf(other)) return true; if (mixinMirror.isSubtypeOf(other)) return true;
} }
@ -234,13 +233,11 @@ class TypeMirrorImpl extends TypedMirror implements TypeMirror {
} }
@override @override
bool isAssignableTo(TypeMirror other) { bool isAssignableTo(TypeMirrorContract other) {
// A type T may be assigned to a type S if either: // A type T may be assigned to a type S if either:
// 1. T is a subtype of S, or // 1. T is a subtype of S, or
// 2. S is dynamic (except for void) // 2. S is dynamic (except for void)
if (other is TypeMirrorImpl && if (other is TypeMirror && other.type == dynamicType && type != voidType) {
other.type == dynamicType &&
type != voidType) {
return true; return true;
} }
return isSubtypeOf(other); return isSubtypeOf(other);
@ -249,7 +246,7 @@ class TypeMirrorImpl extends TypedMirror implements TypeMirror {
@override @override
bool operator ==(Object other) { bool operator ==(Object other) {
if (identical(this, other)) return true; if (identical(this, other)) return true;
if (other is! TypeMirrorImpl) return false; if (other is! TypeMirror) return false;
return type == other.type && return type == other.type &&
name == other.name && name == other.name &&

View file

@ -1,18 +1,18 @@
import '../mirrors.dart'; import 'package:platform_contracts/contracts.dart'
import '../metadata.dart'; hide PropertyMetadata, MethodMetadata, ConstructorMetadata;
import 'base_mirror.dart'; import 'package:platform_reflection/mirrors.dart';
import 'type_mirror_impl.dart';
/// Implementation of [TypeVariableMirror] that provides reflection on type variables. /// Implementation of [TypeVariableMirrorContract] that provides reflection on type variables.
class TypeVariableMirrorImpl extends TypedMirror implements TypeVariableMirror { class TypeVariableMirror extends TypedMirror
final TypeMirror _upperBound; implements TypeVariableMirrorContract {
final TypeMirrorContract _upperBound;
TypeVariableMirrorImpl({ TypeVariableMirror({
required Type type, required Type type,
required String name, required String name,
required TypeMirror upperBound, required TypeMirrorContract upperBound,
DeclarationMirror? owner, DeclarationMirrorContract? owner,
List<InstanceMirror> metadata = const [], List<InstanceMirrorContract> metadata = const [],
}) : _upperBound = upperBound, }) : _upperBound = upperBound,
super( super(
type: type, type: type,
@ -22,7 +22,7 @@ class TypeVariableMirrorImpl extends TypedMirror implements TypeVariableMirror {
); );
@override @override
TypeMirror get upperBound => _upperBound; TypeMirrorContract get upperBound => _upperBound;
@override @override
bool get hasReflectedType => true; bool get hasReflectedType => true;
@ -31,42 +31,39 @@ class TypeVariableMirrorImpl extends TypedMirror implements TypeVariableMirror {
Type get reflectedType => type; Type get reflectedType => type;
@override @override
List<TypeVariableMirror> get typeVariables => const []; List<TypeVariableMirrorContract> get typeVariables => const [];
@override @override
List<TypeMirror> get typeArguments => const []; List<TypeMirrorContract> get typeArguments => const [];
@override @override
bool get isOriginalDeclaration => true; bool get isOriginalDeclaration => true;
@override @override
TypeMirror get originalDeclaration => this; TypeMirrorContract get originalDeclaration => this;
@override @override
bool isSubtypeOf(TypeMirror other) { bool isSubtypeOf(TypeMirrorContract other) {
if (identical(this, other)) return true; if (identical(this, other)) return true;
return _upperBound.isSubtypeOf(other); return _upperBound.isSubtypeOf(other);
} }
@override @override
bool isAssignableTo(TypeMirror other) { bool isAssignableTo(TypeMirrorContract other) {
if (identical(this, other)) return true; if (identical(this, other)) return true;
return _upperBound.isAssignableTo(other); return _upperBound.isAssignableTo(other);
} }
@override
Map<String, PropertyMetadata> get properties => const {}; Map<String, PropertyMetadata> get properties => const {};
@override
Map<String, MethodMetadata> get methods => const {}; Map<String, MethodMetadata> get methods => const {};
@override
List<ConstructorMetadata> get constructors => const []; List<ConstructorMetadata> get constructors => const [];
@override @override
bool operator ==(Object other) { bool operator ==(Object other) {
if (identical(this, other)) return true; if (identical(this, other)) return true;
if (other is! TypeVariableMirrorImpl) return false; if (other is! TypeVariableMirror) return false;
return type == other.type && return type == other.type &&
name == other.name && name == other.name &&

View file

@ -1,25 +1,25 @@
import 'dart:core'; import 'dart:core';
import '../mirrors.dart'; import 'package:platform_contracts/contracts.dart';
import 'base_mirror.dart'; import 'package:platform_reflection/mirrors.dart';
import 'type_mirror_impl.dart';
/// Implementation of [VariableMirror] that provides reflection on variables. /// Implementation of [VariableMirrorContract] that provides reflection on variables.
class VariableMirrorImpl extends MutableOwnerMirror implements VariableMirror { class VariableMirror extends MutableOwnerMirror
final TypeMirror _type; implements VariableMirrorContract {
final TypeMirrorContract _type;
final String _name; final String _name;
final bool _isStatic; final bool _isStatic;
final bool _isFinal; final bool _isFinal;
final bool _isConst; final bool _isConst;
final List<InstanceMirror> _metadata; final List<InstanceMirrorContract> _metadata;
VariableMirrorImpl({ VariableMirror({
required String name, required String name,
required TypeMirror type, required TypeMirrorContract type,
DeclarationMirror? owner, DeclarationMirrorContract? owner,
bool isStatic = false, bool isStatic = false,
bool isFinal = false, bool isFinal = false,
bool isConst = false, bool isConst = false,
List<InstanceMirror> metadata = const [], List<InstanceMirrorContract> metadata = const [],
}) : _name = name, }) : _name = name,
_type = type, _type = type,
_isStatic = isStatic, _isStatic = isStatic,
@ -45,10 +45,10 @@ class VariableMirrorImpl extends MutableOwnerMirror implements VariableMirror {
bool get isPrivate => _name.startsWith('_'); bool get isPrivate => _name.startsWith('_');
@override @override
bool get isTopLevel => owner is LibraryMirror; bool get isTopLevel => owner is LibraryMirrorContract;
@override @override
TypeMirror get type => _type; TypeMirrorContract get type => _type;
@override @override
bool get isStatic => _isStatic; bool get isStatic => _isStatic;
@ -60,12 +60,12 @@ class VariableMirrorImpl extends MutableOwnerMirror implements VariableMirror {
bool get isConst => _isConst; bool get isConst => _isConst;
@override @override
List<InstanceMirror> get metadata => List.unmodifiable(_metadata); List<InstanceMirrorContract> get metadata => List.unmodifiable(_metadata);
@override @override
bool operator ==(Object other) { bool operator ==(Object other) {
if (identical(this, other)) return true; if (identical(this, other)) return true;
if (other is! VariableMirrorImpl) return false; if (other is! VariableMirror) return false;
return _name == other._name && return _name == other._name &&
_type == other._type && _type == other._type &&
@ -98,21 +98,21 @@ class VariableMirrorImpl extends MutableOwnerMirror implements VariableMirror {
} }
} }
/// Implementation of [VariableMirror] specifically for fields. /// Implementation of [VariableMirrorContract] specifically for fields.
class FieldMirrorImpl extends VariableMirrorImpl { class FieldMirrorImpl extends VariableMirror {
final bool _isReadable; final bool _isReadable;
final bool _isWritable; final bool _isWritable;
FieldMirrorImpl({ FieldMirrorImpl({
required String name, required String name,
required TypeMirror type, required TypeMirrorContract type,
DeclarationMirror? owner, DeclarationMirrorContract? owner,
bool isStatic = false, bool isStatic = false,
bool isFinal = false, bool isFinal = false,
bool isConst = false, bool isConst = false,
bool isReadable = true, bool isReadable = true,
bool isWritable = true, bool isWritable = true,
List<InstanceMirror> metadata = const [], List<InstanceMirrorContract> metadata = const [],
}) : _isReadable = isReadable, }) : _isReadable = isReadable,
_isWritable = isWritable, _isWritable = isWritable,
super( super(

View file

@ -1,19 +0,0 @@
/// Represents the void type in our reflection system.
class VoidType implements Type {
const VoidType._();
/// The singleton instance representing void.
static const instance = VoidType._();
@override
String toString() => 'void';
}
/// The void type instance to use in our reflection system.
const voidType = VoidType.instance;
/// Extension to check if a Type is void.
extension TypeExtensions on Type {
/// Whether this type represents void.
bool get isVoid => this == voidType;
}

View file

@ -1,5 +1,5 @@
import 'dart:isolate'; import 'dart:isolate';
import 'package:platform_reflection/reflection.dart'; import 'package:platform_reflection/mirrors.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
// Function to run in isolate // Function to run in isolate
@ -50,8 +50,8 @@ void main() {
receivePort.sendPort, receivePort.sendPort,
); );
final isolateMirror = reflector.reflectIsolate(isolate, 'test-isolate') final isolateMirror =
as IsolateMirrorImpl; reflector.reflectIsolate(isolate, 'test-isolate') as IsolateMirror;
// Test pause/resume // Test pause/resume
await isolateMirror.pause(); await isolateMirror.pause();

View file

@ -1,4 +1,5 @@
import 'package:platform_reflection/reflection.dart'; import 'package:platform_contracts/contracts.dart';
import 'package:platform_reflection/mirrors.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
// Top-level function for testing // Top-level function for testing
@ -44,14 +45,15 @@ void main() {
expect(declarations, isNotEmpty); expect(declarations, isNotEmpty);
// Check for top-level function // Check for top-level function
final addFunction = declarations[const Symbol('add')] as MethodMirror; final addFunction =
declarations[const Symbol('add')] as MethodMirrorContract;
expect(addFunction, isNotNull); expect(addFunction, isNotNull);
expect(addFunction.isStatic, isTrue); expect(addFunction.isStatic, isTrue);
expect(addFunction.parameters.length, equals(2)); expect(addFunction.parameters.length, equals(2));
// Check for top-level variable // Check for top-level variable
final greetingVar = final greetingVar =
declarations[const Symbol('greeting')] as VariableMirror; declarations[const Symbol('greeting')] as VariableMirrorContract;
expect(greetingVar, isNotNull); expect(greetingVar, isNotNull);
expect(greetingVar.isStatic, isTrue); expect(greetingVar.isStatic, isTrue);
expect(greetingVar.isConst, isTrue); expect(greetingVar.isConst, isTrue);

View file

@ -1,4 +1,5 @@
import 'package:platform_reflection/reflection.dart'; import 'package:platform_contracts/contracts.dart' hide PropertyMetadata;
import 'package:platform_reflection/mirrors.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
@reflectable @reflectable
@ -9,12 +10,12 @@ class TestClass {
void main() { void main() {
group('MirrorSystem', () { group('MirrorSystem', () {
late RuntimeReflector reflector; //late RuntimeReflector reflector;
late MirrorSystem mirrorSystem; late MirrorSystemContract mirrorSystem;
setUp(() { setUp(() {
reflector = RuntimeReflector.instance; //reflector = RuntimeReflector.instance;
mirrorSystem = reflector.currentMirrorSystem; mirrorSystem = MirrorSystem.instance;
// Register test class // Register test class
Reflector.registerType(TestClass); Reflector.registerType(TestClass);

View file

@ -1,4 +1,5 @@
import 'package:platform_reflection/reflection.dart'; import 'package:platform_contracts/contracts.dart';
import 'package:platform_reflection/mirrors.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
@reflectable @reflectable
@ -53,7 +54,7 @@ void main() {
group('Property Access', () { group('Property Access', () {
late Person person; late Person person;
late InstanceMirror mirror; late InstanceMirrorContract mirror;
setUp(() { setUp(() {
Reflector.register(Person); Reflector.register(Person);
@ -90,7 +91,7 @@ void main() {
group('Method Invocation', () { group('Method Invocation', () {
late Person person; late Person person;
late InstanceMirror mirror; late InstanceMirrorContract mirror;
setUp(() { setUp(() {
Reflector.register(Person); Reflector.register(Person);

View file

@ -1,4 +1,4 @@
import 'package:platform_reflection/reflection.dart'; import 'package:platform_reflection/mirrors.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
@reflectable @reflectable

View file

@ -1,4 +1,4 @@
import 'package:platform_reflection/reflection.dart'; import 'package:platform_reflection/mirrors.dart';
import 'collection.dart'; import 'collection.dart';
/// A proxy class for higher-order collection operations. /// A proxy class for higher-order collection operations.

View file

@ -1,4 +1,4 @@
import 'package:platform_reflection/reflection.dart'; import 'package:platform_reflection/mirrors.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:platform_collections/src/collection.dart'; import 'package:platform_collections/src/collection.dart';
import 'package:platform_collections/src/higher_order_collection_proxy.dart'; import 'package:platform_collections/src/higher_order_collection_proxy.dart';

View file

@ -8,10 +8,10 @@
*/ */
/// Base mirror interface /// Base mirror interface
abstract class Mirror {} abstract class MirrorContract {}
/// Base declaration mirror interface /// Base declaration mirror interface
abstract class DeclarationMirror implements Mirror { abstract class DeclarationMirrorContract implements MirrorContract {
/// The simple name for this Dart language entity. /// The simple name for this Dart language entity.
Symbol get simpleName; Symbol get simpleName;
@ -19,7 +19,7 @@ abstract class DeclarationMirror implements Mirror {
Symbol get qualifiedName; Symbol get qualifiedName;
/// A mirror on the owner of this Dart language entity. /// A mirror on the owner of this Dart language entity.
DeclarationMirror? get owner; DeclarationMirrorContract? get owner;
/// Whether this declaration is library private. /// Whether this declaration is library private.
bool get isPrivate; bool get isPrivate;
@ -28,29 +28,30 @@ abstract class DeclarationMirror implements Mirror {
bool get isTopLevel; bool get isTopLevel;
/// A list of the metadata associated with this declaration. /// A list of the metadata associated with this declaration.
List<InstanceMirror> get metadata; List<InstanceMirrorContract> get metadata;
/// The name of this declaration. /// The name of this declaration.
String get name; String get name;
} }
/// Base object mirror interface /// Base object mirror interface
abstract class ObjectMirror implements Mirror { abstract class ObjectMirrorContract implements MirrorContract {
/// Invokes the named function and returns a mirror on the result. /// Invokes the named function and returns a mirror on the result.
InstanceMirror invoke(Symbol memberName, List<dynamic> positionalArguments, InstanceMirrorContract invoke(
Symbol memberName, List<dynamic> positionalArguments,
[Map<Symbol, dynamic> namedArguments = const {}]); [Map<Symbol, dynamic> namedArguments = const {}]);
/// Invokes a getter and returns a mirror on the result. /// Invokes a getter and returns a mirror on the result.
InstanceMirror getField(Symbol fieldName); InstanceMirrorContract getField(Symbol fieldName);
/// Invokes a setter and returns a mirror on the result. /// Invokes a setter and returns a mirror on the result.
InstanceMirror setField(Symbol fieldName, dynamic value); InstanceMirrorContract setField(Symbol fieldName, dynamic value);
} }
/// Base instance mirror interface /// Base instance mirror interface
abstract class InstanceMirror implements ObjectMirror { abstract class InstanceMirrorContract implements ObjectMirrorContract {
/// A mirror on the type of the instance. /// A mirror on the type of the instance.
ClassMirror get type; ClassMirrorContract get type;
/// Whether this mirror's reflectee is accessible. /// Whether this mirror's reflectee is accessible.
bool get hasReflectee; bool get hasReflectee;
@ -60,12 +61,13 @@ abstract class InstanceMirror implements ObjectMirror {
} }
/// Base class mirror interface /// Base class mirror interface
abstract class ClassMirror implements TypeMirror, ObjectMirror { abstract class ClassMirrorContract
implements TypeMirrorContract, ObjectMirrorContract {
/// A mirror on the superclass. /// A mirror on the superclass.
ClassMirror? get superclass; ClassMirrorContract? get superclass;
/// Mirrors on the superinterfaces. /// Mirrors on the superinterfaces.
List<ClassMirror> get superinterfaces; List<ClassMirrorContract> get superinterfaces;
/// Whether this class is abstract. /// Whether this class is abstract.
bool get isAbstract; bool get isAbstract;
@ -74,25 +76,25 @@ abstract class ClassMirror implements TypeMirror, ObjectMirror {
bool get isEnum; bool get isEnum;
/// The declarations in this class. /// The declarations in this class.
Map<Symbol, DeclarationMirror> get declarations; Map<Symbol, DeclarationMirrorContract> get declarations;
/// The instance members of this class. /// The instance members of this class.
Map<Symbol, MethodMirror> get instanceMembers; Map<Symbol, MethodMirrorContract> get instanceMembers;
/// The static members of this class. /// The static members of this class.
Map<Symbol, MethodMirror> get staticMembers; Map<Symbol, MethodMirrorContract> get staticMembers;
/// Creates a new instance using the specified constructor. /// Creates a new instance using the specified constructor.
InstanceMirror newInstance( InstanceMirrorContract newInstance(
Symbol constructorName, List<dynamic> positionalArguments, Symbol constructorName, List<dynamic> positionalArguments,
[Map<Symbol, dynamic> namedArguments = const {}]); [Map<Symbol, dynamic> namedArguments = const {}]);
/// Whether this class is a subclass of [other]. /// Whether this class is a subclass of [other].
bool isSubclassOf(ClassMirror other); bool isSubclassOf(ClassMirrorContract other);
} }
/// Base type mirror interface /// Base type mirror interface
abstract class TypeMirror implements DeclarationMirror { abstract class TypeMirrorContract implements DeclarationMirrorContract {
/// Whether this mirror reflects a type available at runtime. /// Whether this mirror reflects a type available at runtime.
bool get hasReflectedType; bool get hasReflectedType;
@ -100,34 +102,34 @@ abstract class TypeMirror implements DeclarationMirror {
Type get reflectedType; Type get reflectedType;
/// Type variables declared on this type. /// Type variables declared on this type.
List<TypeVariableMirror> get typeVariables; List<TypeVariableMirrorContract> get typeVariables;
/// Type arguments provided to this type. /// Type arguments provided to this type.
List<TypeMirror> get typeArguments; List<TypeMirrorContract> get typeArguments;
/// Whether this is the original declaration of this type. /// Whether this is the original declaration of this type.
bool get isOriginalDeclaration; bool get isOriginalDeclaration;
/// A mirror on the original declaration of this type. /// A mirror on the original declaration of this type.
TypeMirror get originalDeclaration; TypeMirrorContract get originalDeclaration;
/// Checks if this type is a subtype of [other]. /// Checks if this type is a subtype of [other].
bool isSubtypeOf(TypeMirror other); bool isSubtypeOf(TypeMirrorContract other);
/// Checks if this type is assignable to [other]. /// Checks if this type is assignable to [other].
bool isAssignableTo(TypeMirror other); bool isAssignableTo(TypeMirrorContract other);
} }
/// Base method mirror interface /// Base method mirror interface
abstract class MethodMirror implements DeclarationMirror { abstract class MethodMirrorContract implements DeclarationMirrorContract {
/// A mirror on the return type. /// A mirror on the return type.
TypeMirror get returnType; TypeMirrorContract get returnType;
/// The source code if available. /// The source code if available.
String? get source; String? get source;
/// Mirrors on the parameters. /// Mirrors on the parameters.
List<ParameterMirror> get parameters; List<ParameterMirrorContract> get parameters;
/// Whether this is a static method. /// Whether this is a static method.
bool get isStatic; bool get isStatic;
@ -170,7 +172,7 @@ abstract class MethodMirror implements DeclarationMirror {
} }
/// Base parameter mirror interface /// Base parameter mirror interface
abstract class ParameterMirror implements VariableMirror { abstract class ParameterMirrorContract implements VariableMirrorContract {
/// Whether this is an optional parameter. /// Whether this is an optional parameter.
bool get isOptional; bool get isOptional;
@ -181,13 +183,13 @@ abstract class ParameterMirror implements VariableMirror {
bool get hasDefaultValue; bool get hasDefaultValue;
/// The default value if this is an optional parameter. /// The default value if this is an optional parameter.
InstanceMirror? get defaultValue; InstanceMirrorContract? get defaultValue;
} }
/// Base variable mirror interface /// Base variable mirror interface
abstract class VariableMirror implements DeclarationMirror { abstract class VariableMirrorContract implements DeclarationMirrorContract {
/// A mirror on the type of this variable. /// A mirror on the type of this variable.
TypeMirror get type; TypeMirrorContract get type;
/// Whether this is a static variable. /// Whether this is a static variable.
bool get isStatic; bool get isStatic;
@ -200,25 +202,26 @@ abstract class VariableMirror implements DeclarationMirror {
} }
/// Base type variable mirror interface /// Base type variable mirror interface
abstract class TypeVariableMirror implements TypeMirror { abstract class TypeVariableMirrorContract implements TypeMirrorContract {
/// A mirror on the upper bound of this type variable. /// A mirror on the upper bound of this type variable.
TypeMirror get upperBound; TypeMirrorContract get upperBound;
} }
/// Base library mirror interface /// Base library mirror interface
abstract class LibraryMirror implements DeclarationMirror, ObjectMirror { abstract class LibraryMirrorContract
implements DeclarationMirrorContract, ObjectMirrorContract {
/// The absolute URI of the library. /// The absolute URI of the library.
Uri get uri; Uri get uri;
/// The declarations in this library. /// The declarations in this library.
Map<Symbol, DeclarationMirror> get declarations; Map<Symbol, DeclarationMirrorContract> get declarations;
/// The imports and exports of this library. /// The imports and exports of this library.
List<LibraryDependencyMirror> get libraryDependencies; List<LibraryDependencyMirrorContract> get libraryDependencies;
} }
/// Base library dependency mirror interface /// Base library dependency mirror interface
abstract class LibraryDependencyMirror implements Mirror { abstract class LibraryDependencyMirrorContract implements MirrorContract {
/// Whether this is an import. /// Whether this is an import.
bool get isImport; bool get isImport;
@ -229,20 +232,20 @@ abstract class LibraryDependencyMirror implements Mirror {
bool get isDeferred; bool get isDeferred;
/// The library containing this dependency. /// The library containing this dependency.
LibraryMirror get sourceLibrary; LibraryMirrorContract get sourceLibrary;
/// The target library of this dependency. /// The target library of this dependency.
LibraryMirror? get targetLibrary; LibraryMirrorContract? get targetLibrary;
/// The prefix if this is a prefixed import. /// The prefix if this is a prefixed import.
Symbol? get prefix; Symbol? get prefix;
/// The show/hide combinators on this dependency. /// The show/hide combinators on this dependency.
List<CombinatorMirror> get combinators; List<CombinatorMirrorContract> get combinators;
} }
/// Base combinator mirror interface /// Base combinator mirror interface
abstract class CombinatorMirror implements Mirror { abstract class CombinatorMirrorContract implements MirrorContract {
/// The identifiers in this combinator. /// The identifiers in this combinator.
List<Symbol> get identifiers; List<Symbol> get identifiers;
@ -252,3 +255,42 @@ abstract class CombinatorMirror implements Mirror {
/// Whether this is a hide combinator. /// Whether this is a hide combinator.
bool get isHide; bool get isHide;
} }
/// An [IsolateMirrorContract] reflects an isolate.
abstract class IsolateMirrorContract implements MirrorContract {
/// A unique name used to refer to the isolate in debugging messages.
String get debugName;
/// Whether this mirror reflects the currently running isolate.
bool get isCurrent;
/// The root library for the reflected isolate.
LibraryMirrorContract get rootLibrary;
}
/// A [MirrorSystemContract] is the main interface used to reflect on a set of libraries.
abstract class MirrorSystemContract {
/// All libraries known to the mirror system.
Map<Uri, LibraryMirrorContract> get libraries;
/// Returns the unique library with the specified name.
LibraryMirrorContract findLibrary(Symbol libraryName);
/// Returns a mirror for the specified class.
ClassMirrorContract reflectClass(Type type);
/// Returns a mirror for the specified type.
TypeMirrorContract reflectType(Type type);
/// A mirror on the isolate associated with this mirror system.
IsolateMirrorContract get isolate;
/// A mirror on the dynamic type.
TypeMirrorContract get dynamicType;
/// A mirror on the void type.
TypeMirrorContract get voidType;
/// A mirror on the Never type.
TypeMirrorContract get neverType;
}

View file

@ -8,7 +8,6 @@
*/ */
import 'base.dart'; import 'base.dart';
import 'metadata.dart';
export 'base.dart'; export 'base.dart';
export 'metadata.dart'; export 'metadata.dart';
@ -16,16 +15,16 @@ export 'metadata.dart';
/// Core reflector contract for type introspection. /// Core reflector contract for type introspection.
abstract class ReflectorContract { abstract class ReflectorContract {
/// Get a class mirror /// Get a class mirror
ClassMirror? reflectClass(Type type); ClassMirrorContract? reflectClass(Type type);
/// Get a type mirror /// Get a type mirror
TypeMirror reflectType(Type type); TypeMirrorContract reflectType(Type type);
/// Get an instance mirror /// Get an instance mirror
InstanceMirror reflect(Object object); InstanceMirrorContract reflect(Object object);
/// Get a library mirror /// Get a library mirror
LibraryMirror reflectLibrary(Uri uri); LibraryMirrorContract reflectLibrary(Uri uri);
/// Create a new instance /// Create a new instance
dynamic createInstance( dynamic createInstance(

View file

@ -1,4 +1,4 @@
import 'package:platform_reflection/reflection.dart'; import 'package:platform_reflection/mirrors.dart';
/// Interface for objects that can provide methods to be mixed in /// Interface for objects that can provide methods to be mixed in
abstract class MacroProvider { abstract class MacroProvider {

View file

@ -1,6 +1,6 @@
import 'package:platform_reflection/reflection.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:platform_macroable/platform_macroable.dart'; import 'package:platform_macroable/platform_macroable.dart';
import 'package:platform_reflection/mirrors.dart';
@reflectable @reflectable
class TestClass with Macroable {} class TestClass with Macroable {}

7
packages/mirrors/.gitignore vendored Normal file
View file

@ -0,0 +1,7 @@
# https://dart.dev/guides/libraries/private-files
# Created by `dart pub`
.dart_tool/
# Avoid committing pubspec.lock for library packages; see
# https://dart.dev/guides/libraries/private-files#pubspeclock.
pubspec.lock

View file

@ -0,0 +1,3 @@
## 1.0.0
- Initial version.

View file

@ -0,0 +1,10 @@
The MIT License (MIT)
The Laravel Framework is Copyright (c) Taylor Otwell
The Fabric Framework is Copyright (c) Vieo, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1 @@
<p align="center"><a href="https://protevus.com" target="_blank"><img src="https://git.protevus.com/protevus/branding/raw/branch/main/protevus-logo-bg.png"></a></p>

View file

@ -0,0 +1,30 @@
# This file configures the static analysis results for your project (errors,
# warnings, and lints).
#
# This enables the 'recommended' set of lints from `package:lints`.
# This set helps identify many issues that may lead to problems when running
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
# style and format.
#
# If you want a smaller set of lints you can change this to specify
# 'package:lints/core.yaml'. These are just the most critical lints
# (the recommended set includes the core lints).
# The core lints are also what is used by pub.dev for scoring packages.
include: package:lints/recommended.yaml
# Uncomment the following section to specify additional rules.
# linter:
# rules:
# - camel_case_types
# analyzer:
# exclude:
# - path/to/excluded/files/**
# For more information about the core and recommended set of lints, see
# https://dart.dev/go/core-lints
# For additional information about configuring this file, see
# https://dart.dev/guides/language/analysis-options

View file

View file

View file

View file

@ -0,0 +1,20 @@
name: platform_mirrors
description: A lightweight, cross-platform reflection system for Dart
version: 0.0.1
homepage: https://protevus.com
documentation: https://docs.protevus.com
repository: https://github.com/protevus/platformo
environment:
sdk: '>=3.0.0 <4.0.0'
dependencies:
platform_contracts: ^0.1.0
meta: ^1.9.0
collection: ^1.17.0
dev_dependencies:
test: ^1.24.0
mockito: ^5.4.0
build_runner: ^2.4.0
lints: ^2.1.0

View file

View file

@ -1,5 +1,5 @@
import 'package:platform_macroable/platform_macroable.dart'; import 'package:platform_macroable/platform_macroable.dart';
import 'package:platform_reflection/reflection.dart'; import 'package:platform_reflection/mirrors.dart';
/// Provides higher-order tap functionality with macro support. /// Provides higher-order tap functionality with macro support.
/// ///

View file

@ -1,5 +1,5 @@
import 'once.dart'; import 'once.dart';
import 'package:platform_reflection/reflection.dart'; import 'package:platform_reflection/mirrors.dart';
/// A class that provides functionality to ensure methods are only executed once. /// A class that provides functionality to ensure methods are only executed once.
/// ///

View file

@ -1,5 +1,5 @@
import 'package:platform_macroable/platform_macroable.dart'; import 'package:platform_macroable/platform_macroable.dart';
import 'package:platform_reflection/reflection.dart'; import 'package:platform_reflection/mirrors.dart';
/// Provides Laravel-like Optional type functionality with macro support. /// Provides Laravel-like Optional type functionality with macro support.
/// ///

View file

@ -1,5 +1,5 @@
import 'package:platform_reflection/reflection.dart'; import 'package:platform_contracts/contracts.dart';
import 'package:platform_reflection/src/core/reflector.dart'; import 'package:platform_reflection/mirrors.dart';
/// Provides reflection utilities for examining types and methods at runtime. /// Provides reflection utilities for examining types and methods at runtime.
class SupportReflector { class SupportReflector {
@ -64,7 +64,7 @@ class SupportReflector {
} }
/// Get the class name of the given parameter's type, if possible. /// Get the class name of the given parameter's type, if possible.
static String? getParameterClassName(ParameterMirror parameter) { static String? getParameterClassName(ParameterMirrorContract parameter) {
final type = parameter.type; final type = parameter.type;
if (!type.hasReflectedType) { if (!type.hasReflectedType) {
@ -75,7 +75,8 @@ class SupportReflector {
} }
/// Get the class names of the given parameter's type, including union types. /// Get the class names of the given parameter's type, including union types.
static List<String> getParameterClassNames(ParameterMirror parameter) { static List<String> getParameterClassNames(
ParameterMirrorContract parameter) {
final type = parameter.type; final type = parameter.type;
final classNames = <String>[]; final classNames = <String>[];
@ -106,13 +107,14 @@ class SupportReflector {
} }
/// Get the given type's class name. /// Get the given type's class name.
static String? _getTypeName(ParameterMirror parameter, TypeMirror type) { static String? _getTypeName(
ParameterMirrorContract parameter, TypeMirrorContract type) {
if (!type.hasReflectedType) { if (!type.hasReflectedType) {
return null; return null;
} }
final name = type.reflectedType.toString(); final name = type.reflectedType.toString();
final declaringClass = parameter.owner as ClassMirror?; final declaringClass = parameter.owner as ClassMirrorContract?;
if (declaringClass != null) { if (declaringClass != null) {
if (name == 'self') { if (name == 'self') {
@ -129,7 +131,7 @@ class SupportReflector {
/// Determine if the parameter's type is a subclass of the given type. /// Determine if the parameter's type is a subclass of the given type.
static bool isParameterSubclassOf( static bool isParameterSubclassOf(
ParameterMirror parameter, String className) { ParameterMirrorContract parameter, String className) {
final type = parameter.type; final type = parameter.type;
if (!type.hasReflectedType) { if (!type.hasReflectedType) {
return false; return false;
@ -145,7 +147,7 @@ class SupportReflector {
/// Determine if the parameter's type is a backed enum with a string backing type. /// Determine if the parameter's type is a backed enum with a string backing type.
static bool isParameterBackedEnumWithStringBackingType( static bool isParameterBackedEnumWithStringBackingType(
ParameterMirror parameter) { ParameterMirrorContract parameter) {
final type = parameter.type; final type = parameter.type;
if (!type.hasReflectedType) { if (!type.hasReflectedType) {
return false; return false;

View file

@ -1,5 +1,5 @@
import 'package:meta/meta.dart'; import 'package:meta/meta.dart';
import 'package:platform_reflection/reflection.dart'; import 'package:platform_reflection/mirrors.dart';
/// A mixin that provides method forwarding functionality. /// A mixin that provides method forwarding functionality.
/// ///

View file

@ -1,4 +1,4 @@
import 'package:platform_reflection/reflection.dart'; import 'package:platform_reflection/mirrors.dart';
/// A trait that provides functionality to reflect on closures. /// A trait that provides functionality to reflect on closures.
mixin ReflectsClosures { mixin ReflectsClosures {

View file

@ -1,7 +1,5 @@
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:platform_support/platform_support.dart'; import 'package:platform_support/platform_support.dart';
import 'package:platform_macroable/platform_macroable.dart';
import 'package:platform_reflection/reflection.dart';
// Test class to use with HigherOrderTapProxy // Test class to use with HigherOrderTapProxy
class TestTarget { class TestTarget {

View file

@ -1,5 +1,5 @@
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:platform_reflection/reflection.dart'; import 'package:platform_reflection/mirrors.dart';
import 'package:platform_support/platform_support.dart'; import 'package:platform_support/platform_support.dart';
void main() { void main() {

View file

@ -1,6 +1,6 @@
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:platform_support/platform_support.dart'; import 'package:platform_support/platform_support.dart';
import 'package:platform_reflection/reflection.dart'; import 'package:platform_reflection/mirrors.dart';
@reflectable @reflectable
class TargetClass { class TargetClass {

View file

@ -1,6 +1,6 @@
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:platform_support/platform_support.dart'; import 'package:platform_support/platform_support.dart';
import 'package:platform_reflection/reflection.dart'; import 'package:platform_reflection/mirrors.dart';
@reflectable @reflectable
class TestObject { class TestObject {

View file

@ -1,11 +1,7 @@
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:platform_contracts/contracts.dart';
import 'package:platform_reflection/mirrors.dart';
import 'package:platform_support/platform_support.dart'; import 'package:platform_support/platform_support.dart';
import 'package:platform_reflection/reflection.dart';
import 'package:platform_reflection/src/core/reflector.dart';
import 'package:platform_reflection/src/mirrors/method_mirror_impl.dart';
import 'package:platform_reflection/src/mirrors/parameter_mirror_impl.dart';
import 'package:platform_reflection/src/mirrors/type_mirror_impl.dart';
import 'package:platform_reflection/src/mirrors/class_mirror_impl.dart';
class TestClass { class TestClass {
void publicMethod() {} void publicMethod() {}
@ -28,29 +24,29 @@ enum BackedEnum {
} }
void main() { void main() {
late ClassMirrorImpl testClassMirror; late ClassMirror testClassMirror;
setUp(() { setUp(() {
// Create type mirrors // Create type mirrors
final voidType = TypeMirrorImpl( final voidType = TypeMirror(
type: Null, // Using Null as a stand-in for void type: Null, // Using Null as a stand-in for void
name: 'void', name: 'void',
owner: null, owner: null,
metadata: const [], metadata: const [],
); );
final stringType = TypeMirrorImpl( final stringType = TypeMirror(
type: String, type: String,
name: 'String', name: 'String',
owner: null, owner: null,
metadata: const [], metadata: const [],
); );
final invocationType = TypeMirrorImpl( final invocationType = TypeMirror(
type: Invocation, type: Invocation,
name: 'Invocation', name: 'Invocation',
owner: null, owner: null,
metadata: const [], metadata: const [],
); );
final objectType = TypeMirrorImpl( final objectType = TypeMirror(
type: Object, type: Object,
name: 'Object', name: 'Object',
owner: null, owner: null,
@ -58,7 +54,7 @@ void main() {
); );
// Create class mirrors // Create class mirrors
testClassMirror = ClassMirrorImpl( testClassMirror = ClassMirror(
type: TestClass, type: TestClass,
name: 'TestClass', name: 'TestClass',
owner: null, owner: null,
@ -69,34 +65,34 @@ void main() {
); );
// Create parameter mirrors // Create parameter mirrors
final selfParam = ParameterMirrorImpl( final selfParam = ParameterMirror(
name: 'self', name: 'self',
type: objectType, // Using Object type for inheritance test type: objectType, // Using Object type for inheritance test
owner: testClassMirror, owner: testClassMirror,
); );
final invocationParam = ParameterMirrorImpl( final invocationParam = ParameterMirror(
name: 'invocation', name: 'invocation',
type: invocationType, type: invocationType,
owner: testClassMirror, owner: testClassMirror,
); );
// Create method mirrors // Create method mirrors
final publicMethodMirror = MethodMirrorImpl( final publicMethodMirror = MethodMirror(
name: 'publicMethod', name: 'publicMethod',
owner: testClassMirror, owner: testClassMirror,
returnType: voidType, returnType: voidType,
parameters: [selfParam], parameters: [selfParam],
); );
final privateMethodMirror = MethodMirrorImpl( final privateMethodMirror = MethodMirror(
name: '_privateMethod', name: '_privateMethod',
owner: testClassMirror, owner: testClassMirror,
returnType: voidType, returnType: voidType,
parameters: [selfParam], parameters: [selfParam],
); );
final noSuchMethodMirror = MethodMirrorImpl( final noSuchMethodMirror = MethodMirror(
name: 'noSuchMethod', name: 'noSuchMethod',
owner: testClassMirror, owner: testClassMirror,
returnType: voidType, returnType: voidType,
@ -208,16 +204,16 @@ void main() {
}); });
test('getParameterClassName returns correct class name', () { test('getParameterClassName returns correct class name', () {
final method = final method = testClassMirror.declarations[Symbol('publicMethod')]
testClassMirror.declarations[Symbol('publicMethod')] as MethodMirror; as MethodMirrorContract;
final param = method.parameters.first; final param = method.parameters.first;
expect(SupportReflector.getParameterClassName(param), equals('Object')); expect(SupportReflector.getParameterClassName(param), equals('Object'));
}); });
test('getParameterClassNames handles union types', () { test('getParameterClassNames handles union types', () {
final method = final method = testClassMirror.declarations[Symbol('publicMethod')]
testClassMirror.declarations[Symbol('publicMethod')] as MethodMirror; as MethodMirrorContract;
final param = method.parameters.first; final param = method.parameters.first;
final classNames = SupportReflector.getParameterClassNames(param); final classNames = SupportReflector.getParameterClassNames(param);
@ -226,8 +222,8 @@ void main() {
}); });
test('isParameterSubclassOf checks inheritance correctly', () { test('isParameterSubclassOf checks inheritance correctly', () {
final method = final method = testClassMirror.declarations[Symbol('publicMethod')]
testClassMirror.declarations[Symbol('publicMethod')] as MethodMirror; as MethodMirrorContract;
final param = method.parameters.first; final param = method.parameters.first;
expect(SupportReflector.isParameterSubclassOf(param, 'Object'), isTrue); expect(SupportReflector.isParameterSubclassOf(param, 'Object'), isTrue);
@ -236,13 +232,13 @@ void main() {
test( test(
'isParameterBackedEnumWithStringBackingType returns true for backed enums', 'isParameterBackedEnumWithStringBackingType returns true for backed enums',
() { () {
final type = TypeMirrorImpl( final type = TypeMirror(
type: BackedEnum, type: BackedEnum,
name: 'BackedEnum', name: 'BackedEnum',
owner: null, owner: null,
metadata: const [], metadata: const [],
); );
final param = ParameterMirrorImpl( final param = ParameterMirror(
name: 'param', name: 'param',
type: type, type: type,
owner: testClassMirror, owner: testClassMirror,
@ -255,13 +251,13 @@ void main() {
test( test(
'isParameterBackedEnumWithStringBackingType returns false for simple enums', 'isParameterBackedEnumWithStringBackingType returns false for simple enums',
() { () {
final type = TypeMirrorImpl( final type = TypeMirror(
type: SimpleEnum, type: SimpleEnum,
name: 'SimpleEnum', name: 'SimpleEnum',
owner: null, owner: null,
metadata: const [], metadata: const [],
); );
final param = ParameterMirrorImpl( final param = ParameterMirror(
name: 'param', name: 'param',
type: type, type: type,
owner: testClassMirror, owner: testClassMirror,
@ -274,13 +270,13 @@ void main() {
test( test(
'isParameterBackedEnumWithStringBackingType returns false for non-enums', 'isParameterBackedEnumWithStringBackingType returns false for non-enums',
() { () {
final type = TypeMirrorImpl( final type = TypeMirror(
type: String, type: String,
name: 'String', name: 'String',
owner: null, owner: null,
metadata: const [], metadata: const [],
); );
final param = ParameterMirrorImpl( final param = ParameterMirror(
name: 'param', name: 'param',
type: type, type: type,
owner: testClassMirror, owner: testClassMirror,

View file

@ -1,6 +1,6 @@
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:platform_support/platform_support.dart'; import 'package:platform_support/platform_support.dart';
import 'package:platform_reflection/reflection.dart'; import 'package:platform_reflection/mirrors.dart';
@reflectable @reflectable
class TappableTest with Tappable { class TappableTest with Tappable {

View file

@ -1,5 +1,5 @@
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:platform_reflection/reflection.dart'; import 'package:platform_reflection/mirrors.dart';
import 'package:platform_support/src/traits/reflects_closures.dart'; import 'package:platform_support/src/traits/reflects_closures.dart';
class TestClass with ReflectsClosures {} class TestClass with ReflectsClosures {}