From 8c2b018c3d74438063b602f9c8f0cede230a9997 Mon Sep 17 00:00:00 2001 From: Patrick Stewart Date: Sat, 21 Dec 2024 11:01:22 -0700 Subject: [PATCH] update: updating documents --- incubation/reflection/README.md | 443 +++--------------- incubation/reflection/doc/capabilities.md | 315 ++++--------- incubation/reflection/doc/index.md | 29 +- .../reflection/doc/mirrors_comparison.md | 216 ++++----- incubation/reflection/doc/quick_start.md | 375 +++------------ incubation/reflection/doc/roadmap.md | 341 +++++--------- .../reflection/doc/technical_specification.md | 362 ++++---------- .../lib/src/mirrors/mirror_system.dart | 22 +- 8 files changed, 535 insertions(+), 1568 deletions(-) diff --git a/incubation/reflection/README.md b/incubation/reflection/README.md index ede1186..d7f0992 100644 --- a/incubation/reflection/README.md +++ b/incubation/reflection/README.md @@ -1,169 +1,47 @@ # Platform Reflection -A powerful cross-platform reflection system for Dart that provides runtime type introspection and manipulation. This implementation offers a carefully balanced approach between functionality and performance, providing reflection capabilities without the limitations of `dart:mirrors`. +A powerful cross-platform reflection system for Dart that serves as a drop-in replacement for `dart:mirrors`. This implementation offers a carefully balanced approach between functionality and performance, providing reflection capabilities with AOT compilation support. ## Table of Contents - [Features](#features) -- [Architecture](#architecture) - [Installation](#installation) -- [Core Components](#core-components) -- [Usage Guide](#usage-guide) -- [Advanced Usage](#advanced-usage) -- [Performance Considerations](#performance-considerations) -- [Migration Guide](#migration-guide) +- [Usage](#usage) - [API Reference](#api-reference) +- [Performance Considerations](#performance-considerations) - [Limitations](#limitations) +- [Migration from dart:mirrors](#migration-from-dartmirrors) - [Contributing](#contributing) - [License](#license) ## Features -### Core Features - ✅ Platform independent reflection system +- ✅ AOT compilation support - ✅ No dependency on `dart:mirrors` -- ✅ Pure runtime reflection -- ✅ Library scanning and reflection -- ✅ Explicit registration for performance -- ✅ Type-safe operations -- ✅ Comprehensive error handling - -### Reflection Capabilities - ✅ Class reflection with inheritance - ✅ Method invocation with named parameters -- ✅ Property access/mutation +- ✅ Property access and mutation - ✅ Constructor resolution and invocation - ✅ Type introspection and relationships -- ✅ Library dependency tracking -- ✅ Parameter inspection and validation -- ✅ Top-level variable support - -### Performance Features -- ✅ Cached class mirrors -- ✅ Optimized type compatibility checking -- ✅ Efficient parameter resolution -- ✅ Smart library scanning -- ✅ Memory-efficient design -- ✅ Lazy initialization support - -## Architecture - -### Core Components - -``` -platform_reflection/ -├── core/ -│ ├── library_scanner.dart # Library scanning and analysis -│ ├── reflector.dart # Central reflection registry -│ ├── runtime_reflector.dart # Runtime reflection implementation -│ └── scanner.dart # Type scanning and analysis -├── mirrors/ -│ ├── base_mirror.dart # Base mirror implementations -│ ├── class_mirror_impl.dart # Class reflection -│ ├── instance_mirror_impl.dart # Instance reflection -│ ├── library_mirror_impl.dart # Library reflection -│ ├── method_mirror_impl.dart # Method reflection -│ └── ... (other mirrors) -├── annotations.dart # Reflection annotations -├── exceptions.dart # Error handling -├── metadata.dart # Metadata definitions -└── types.dart # Special type implementations -``` - -### Design Principles - -1. **Explicit Registration** - - Clear registration of reflectable types - - Controlled reflection surface - - Optimized runtime performance - -2. **Type Safety** - - Strong type checking - - Compile-time validations - - Runtime type verification - -3. **Performance First** - - Minimal runtime overhead - - Efficient metadata storage - - Optimized lookup mechanisms - -4. **Platform Independence** - - Cross-platform compatibility - - No platform-specific dependencies - - Consistent behavior +- ✅ Explicit registration for performance +- ✅ Basic generic type support +- ✅ Comprehensive error handling ## Installation +Add this to your package's `pubspec.yaml` file: + ```yaml dependencies: platform_reflection: ^0.1.0 ``` -## Core Components +## Usage -### Reflector +### Registration -Central management class for reflection operations: - -```dart -class Reflector { - // Type registration - static void register(Type type); - static void registerProperty(Type type, String name, Type propertyType); - static void registerMethod(Type type, String name, List parameterTypes); - static void registerConstructor(Type type, String name, {Function? creator}); - - // Metadata access - static TypeMetadata? getTypeMetadata(Type type); - static Map? getPropertyMetadata(Type type); - static Map? getMethodMetadata(Type type); - - // Utility methods - static void reset(); - static bool isReflectable(Type type); -} -``` - -### RuntimeReflector - -Runtime reflection implementation: - -```dart -class RuntimeReflector { - // Instance creation - InstanceMirror createInstance(Type type, { - List? positionalArgs, - Map? namedArgs, - String? constructorName, - }); - - // Reflection operations - InstanceMirror reflect(Object object); - ClassMirror reflectClass(Type type); - TypeMirror reflectType(Type type); - LibraryMirror reflectLibrary(Uri uri); -} -``` - -### LibraryScanner - -Library scanning and analysis: - -```dart -class LibraryScanner { - // Library scanning - static LibraryInfo scanLibrary(Uri uri); - - // Analysis methods - static List getTopLevelFunctions(Uri uri); - static List getTopLevelVariables(Uri uri); - static List getDependencies(Uri uri); -} -``` - -## Usage Guide - -### Basic Registration +Unlike `dart:mirrors`, Platform Reflection requires explicit registration of classes and their members. This enables AOT compilation support and fine-grained control over reflection. ```dart @reflectable @@ -171,71 +49,53 @@ class User { String name; int age; final String id; + List tags; - User(this.name, this.age, {required this.id}); + User(this.name, this.age, {required this.id, List? tags}) + : tags = tags ?? []; - void birthday() { - age++; + String greet() => "Hi $name!"; + + void addTag(String tag) { + tags.add(tag); } - String greet(String greeting) { - return '$greeting $name!'; - } + String getName() => name; } -// Register class and members void registerUser() { Reflector.register(User); - - // Register properties Reflector.registerProperty(User, 'name', String); Reflector.registerProperty(User, 'age', int); Reflector.registerProperty(User, 'id', String, isWritable: false); + Reflector.registerProperty(User, 'tags', List, isWritable: false); - // Register methods - Reflector.registerMethod( - User, - 'birthday', - [], - true, - parameterNames: [], - isRequired: [], - ); + Reflector.registerMethod(User, 'greet', [], false); + Reflector.registerMethod(User, 'addTag', [String], true); + Reflector.registerMethod(User, 'getName', [], false); - Reflector.registerMethod( - User, - 'greet', - [String], - false, - parameterNames: ['greeting'], - isRequired: [true], - ); - - // Register constructor Reflector.registerConstructor( User, '', - parameterTypes: [String, int, String], - parameterNames: ['name', 'age', 'id'], - isRequired: [true, true, true], - isNamed: [false, false, true], - creator: (String name, int age, {required String id}) => - User(name, age, id: id), + parameterTypes: [String, int, String, List], + parameterNames: ['name', 'age', 'id', 'tags'], + isRequired: [true, true, true, false], + isNamed: [false, false, true, true], ); } ``` -### Instance Manipulation +### Reflection Operations ```dart -void manipulateInstance() { +void demonstrateReflection() { final reflector = RuntimeReflector.instance; // Create instance final user = reflector.createInstance( User, - positionalArgs: ['John', 30], - namedArgs: {'id': '123'}, + positionalArgs: ['John Doe', 30], + namedArgs: {'id': 'user1', 'tags': ['admin', 'user']}, ) as User; // Get mirror @@ -243,195 +103,20 @@ void manipulateInstance() { // Property access final name = mirror.getField(const Symbol('name')).reflectee as String; - final age = mirror.getField(const Symbol('age')).reflectee as int; // Property modification - mirror.setField(const Symbol('name'), 'Jane'); - mirror.setField(const Symbol('age'), 31); + mirror.setField(const Symbol('age'), 25); // Method invocation - mirror.invoke(const Symbol('birthday'), []); - final greeting = mirror.invoke( - const Symbol('greet'), - ['Hello'], - ).reflectee as String; -} -``` - -### Library Reflection - -```dart -void reflectLibrary() { - final reflector = RuntimeReflector.instance; + final greeting = mirror.invoke(const Symbol('greet'), []).reflectee as String; - // Get library mirror - final library = reflector.reflectLibrary( - Uri.parse('package:myapp/src/models.dart') - ); + // Type information + final classMirror = reflector.reflectClass(User); + print('Type name: ${classMirror.name}'); - // Access top-level function - final result = library.invoke( - const Symbol('utilityFunction'), - [arg1, arg2], - ).reflectee; - - // Access top-level variable - final value = library.getField(const Symbol('constant')).reflectee; - - // Get library dependencies - final dependencies = library.libraryDependencies; - for (final dep in dependencies) { - print('Import: ${dep.targetLibrary.uri}'); - print('Is deferred: ${dep.isDeferred}'); - } -} -``` - -### Type Relationships - -```dart -void checkTypes() { - final reflector = RuntimeReflector.instance; - - // Get class mirrors - final userMirror = reflector.reflectClass(User); - final baseMirror = reflector.reflectClass(BaseClass); - - // Check inheritance - final isSubclass = userMirror.isSubclassOf(baseMirror); - - // Check type compatibility - final isCompatible = userMirror.isAssignableTo(baseMirror); - - // Get superclass - final superclass = userMirror.superclass; - - // Get interfaces - final interfaces = userMirror.interfaces; -} -``` - -## Advanced Usage - -### Generic Type Handling - -```dart -@reflectable -class Container { - T value; - Container(this.value); -} - -void handleGenericType() { - Reflector.register(Container); - - // Register with specific type - final stringContainer = reflector.createInstance( - Container, - positionalArgs: ['Hello'], - ) as Container; - - final mirror = reflector.reflect(stringContainer); - final value = mirror.getField(const Symbol('value')).reflectee as String; -} -``` - -### Error Handling - -```dart -void demonstrateErrorHandling() { - try { - // Attempt to reflect unregistered type - reflector.reflect(UnregisteredClass()); - } on NotReflectableException catch (e) { - print('Type not registered: $e'); - } - - try { - // Attempt to access non-existent member - final mirror = reflector.reflect(user); - mirror.getField(const Symbol('nonexistent')); - } on MemberNotFoundException catch (e) { - print('Member not found: $e'); - } - - try { - // Attempt invalid method invocation - final mirror = reflector.reflect(user); - mirror.invoke(const Symbol('greet'), [42]); // Wrong argument type - } on InvalidArgumentsException catch (e) { - print('Invalid arguments: $e'); - } -} -``` - -## Performance Considerations - -### Registration Impact - -- Explicit registration adds startup cost -- Improved runtime performance -- Reduced memory usage -- Controlled reflection surface - -### Optimization Techniques - -1. **Lazy Loading** - ```dart - // Only register when needed - if (Reflector.getTypeMetadata(User) == null) { - registerUser(); - } - ``` - -2. **Metadata Caching** - ```dart - // Cache metadata access - final metadata = Reflector.getTypeMetadata(User); - final properties = metadata.properties; - final methods = metadata.methods; - ``` - -3. **Instance Reuse** - ```dart - // Reuse instance mirrors - final mirror = reflector.reflect(user); - // Store mirror for repeated use - ``` - -### Memory Management - -- Cached class mirrors -- Efficient parameter resolution -- Smart library scanning -- Minimal metadata storage - -## Migration Guide - -### From dart:mirrors - -```dart -// Old dart:mirrors code -import 'dart:mirrors'; - -final mirror = reflect(instance); -final value = mirror.getField(#propertyName).reflectee; - -// New platform_reflection code -import 'package:platform_reflection/reflection.dart'; - -final mirror = reflector.reflect(instance); -final value = mirror.getField(const Symbol('propertyName')).reflectee; -``` - -### Registration Requirements - -```dart -// Add registration code -void registerTypes() { - Reflector.register(MyClass); - Reflector.registerProperty(MyClass, 'property', String); - Reflector.registerMethod(MyClass, 'method', [int]); + // Type relationships + final entityType = reflector.reflectType(Entity); + print('User is subtype of Entity: ${classMirror.isSubclassOf(entityType)}'); } ``` @@ -439,9 +124,8 @@ void registerTypes() { ### Core Classes -- `Reflector`: Central reflection management +- `Reflector`: Static class for registration and metadata management - `RuntimeReflector`: Runtime reflection operations -- `LibraryScanner`: Library scanning and analysis ### Mirrors @@ -460,33 +144,38 @@ void registerTypes() { ### Exceptions -- `NotReflectableException` -- `ReflectionException` -- `InvalidArgumentsException` -- `MemberNotFoundException` +- `ReflectionException`: Base exception for reflection errors +- `NotReflectableException`: Thrown when attempting to reflect on an unregistered type + +## Performance Considerations + +- Explicit registration adds startup cost but improves runtime performance +- Cached class mirrors for efficient repeated use +- Minimal metadata storage for reduced memory footprint +- AOT compilation support allows for better optimization ## Limitations -Current Implementation Gaps: +- Requires explicit registration of reflectable types and members +- Limited support for complex generic types +- No support for extension methods +- No cross-package private member access -1. **Type System** - - Limited generic variance support - - Basic type relationship checking +## Migration from dart:mirrors -2. **Reflection Features** - - No extension method support - - Limited annotation metadata - - No cross-package private member access +To migrate from `dart:mirrors` to Platform Reflection: -3. **Language Features** - - No operator overloading reflection - - No dynamic code generation - - Limited mixin support +1. Replace `import 'dart:mirrors'` with `import 'package:platform_reflection/mirrors.dart'`. +2. Add `@reflectable` annotation to classes you want to reflect on. +3. Implement a registration function for each reflectable class. +4. Call registration functions at the start of your application. +5. Replace `MirrorSystem.reflect()` with `RuntimeReflector.instance.reflect()`. +6. Update any code that relies on automatic discovery of classes or members. ## Contributing -See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed contribution guidelines. +Contributions are welcome! Please see our [Contributing Guidelines](CONTRIBUTING.md) for more details. ## License -MIT License - see [LICENSE](LICENSE) for details. +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. diff --git a/incubation/reflection/doc/capabilities.md b/incubation/reflection/doc/capabilities.md index 8b1a3bc..db838fe 100644 --- a/incubation/reflection/doc/capabilities.md +++ b/incubation/reflection/doc/capabilities.md @@ -1,203 +1,102 @@ # Platform Reflection Capabilities +This document outlines the key capabilities of the Platform Reflection library, demonstrating its features and usage patterns. + ## Core Reflection Features -### 1. Library Reflection +### 1. Class Reflection ```dart -// Library reflection support -final library = LibraryMirrorImpl.withDeclarations( - name: 'my_library', - uri: Uri.parse('package:my_package/my_library.dart'), -); +@reflectable +class User { + String name; + int age; + final String id; + List tags; -// Access top-level members -final greeting = library.getField(const Symbol('greeting')).reflectee; -final sum = library.invoke( - const Symbol('add'), - [1, 2], -).reflectee; + User(this.name, this.age, {required this.id, List? tags}) + : tags = tags ?? []; + + String greet() => "Hi $name!"; + void addTag(String tag) => tags.add(tag); + String getName() => name; +} + +// Registration +Reflector.register(User); +Reflector.registerProperty(User, 'name', String); +Reflector.registerProperty(User, 'age', int); +Reflector.registerProperty(User, 'id', String, isWritable: false); +Reflector.registerProperty(User, 'tags', List, isWritable: false); +Reflector.registerMethod(User, 'greet', [], false); +Reflector.registerMethod(User, 'addTag', [String], true); +Reflector.registerMethod(User, 'getName', [], false); +Reflector.registerConstructor(User, '', + parameterTypes: [String, int, String, List], + parameterNames: ['name', 'age', 'id', 'tags'], + isRequired: [true, true, true, false], + isNamed: [false, false, true, true], +); ``` -### 2. Isolate Support +### 2. Instance Creation and Manipulation ```dart -// Current isolate reflection -final current = IsolateMirrorImpl.current(rootLibrary); +final reflector = RuntimeReflector.instance; -// Other isolate reflection -final other = IsolateMirrorImpl.other( - isolate, - 'worker', - rootLibrary, -); +// Create instance +final user = reflector.createInstance( + User, + positionalArgs: ['John Doe', 30], + namedArgs: {'id': 'user1', 'tags': ['admin', 'user']}, +) as User; -// Isolate control -await other.pause(); -await other.resume(); -await other.kill(); +// Get mirror +final mirror = reflector.reflect(user); -// Error handling -other.addErrorListener((error, stack) { - print('Error in isolate: $error\n$stack'); +// Property access and modification +print('Name: ${mirror.getField(const Symbol('name')).reflectee}'); +mirror.setField(const Symbol('name'), 'Jane Doe'); + +// Method invocation +final greeting = mirror.invoke(const Symbol('greet'), []).reflectee as String; +mirror.invoke(const Symbol('addTag'), ['vip']); +``` + +### 3. Type Information +```dart +final classMirror = reflector.reflectClass(User); + +print('Type name: ${classMirror.name}'); + +// Properties +classMirror.declarations.values + .whereType() + .forEach((prop) { + print('Property: ${prop.name}: ${prop.type.name}'); + if (!prop.isFinal && !prop.isWritable) print(' (read-only)'); }); -// Exit handling -other.addExitListener((message) { - print('Isolate exited with: $message'); +// Methods +classMirror.declarations.values + .whereType() + .where((method) => !method.isConstructor) + .forEach((method) { + print('Method: ${method.name}'); }); -``` -### 3. Type System -```dart -// Special types -final voidType = VoidType.instance; -final dynamicType = DynamicType.instance; -final neverType = NeverType.instance; - -// Type checking -final isVoid = type.isVoid; -final isDynamic = type.isDynamic; -final isNever = type.isNever; -``` - -### 4. Metadata System -```dart -// Parameter metadata -final param = ParameterMetadata( - name: 'id', - type: int, - isRequired: true, - isNamed: false, - defaultValue: 0, - attributes: [deprecated], -); - -// Property metadata -final prop = PropertyMetadata( - name: 'name', - type: String, - isReadable: true, - isWritable: true, - attributes: [override], -); - -// Method metadata -final method = MethodMetadata( - name: 'calculate', - parameterTypes: [int, double], - parameters: [...], - isStatic: false, - returnsVoid: false, - attributes: [deprecated], -); -``` - -### 5. Constructor Support -```dart -// Constructor metadata -final ctor = ConstructorMetadata( - name: 'named', - parameterTypes: [String, int], - parameters: [...], - parameterNames: ['name', 'age'], - attributes: [...], -); - -// Validation -final valid = ctor.validateArguments(['John', 42]); -``` - -### 6. Type Metadata -```dart -// Full type information -final type = TypeMetadata( - type: User, - name: 'User', - properties: {...}, - methods: {...}, - constructors: [...], - supertype: Person, - interfaces: [Comparable], - attributes: [serializable], -); - -// Member access -final prop = type.getProperty('name'); -final method = type.getMethod('greet'); -final ctor = type.getConstructor('guest'); -``` - -## Advanced Features - -### 1. Library Dependencies -```dart -final deps = library.libraryDependencies; -for (var dep in deps) { - if (dep.isImport) { - print('Imports: ${dep.targetLibrary?.uri}'); - } -} -``` - -### 2. Declaration Access -```dart -final decls = library.declarations; -for (var decl in decls.values) { - if (decl is MethodMirror) { - print('Method: ${decl.simpleName}'); - } else if (decl is VariableMirror) { - print('Variable: ${decl.simpleName}'); - } -} -``` - -### 3. Function Metadata -```dart -final func = FunctionMetadata( - parameters: [...], - returnsVoid: false, - returnType: int, -); - -final valid = func.validateArguments([1, 2.0]); -``` - -### 4. Reflection Registry -```dart -// Type registration -ReflectionRegistry.registerType(User); - -// Member registration -ReflectionRegistry.registerProperty( - User, - 'name', - String, - isReadable: true, - isWritable: true, -); - -ReflectionRegistry.registerMethod( - User, - 'greet', - [String], - false, -); - -ReflectionRegistry.registerConstructor( - User, - 'guest', - factory, -); +// Constructors +classMirror.declarations.values + .whereType() + .where((method) => method.isConstructor) + .forEach((constructor) { + print('Constructor: ${constructor.name}'); +}); ``` ## Error Handling ```dart try { - // Reflection operations -} on MemberNotFoundException catch (e) { - print('Member not found: ${e.memberName} on ${e.type}'); -} on InvalidArgumentsException catch (e) { - print('Invalid arguments for ${e.memberName}'); + final mirror = reflector.reflect(unregisteredInstance); } on ReflectionException catch (e) { print('Reflection error: ${e.message}'); } @@ -222,66 +121,34 @@ try { - Fast lookup mechanisms - Memory-conscious design -3. **Cross-isolate Performance** - - Minimal serialization overhead - - Efficient isolate communication - - Controlled resource usage - -## Security Features - -1. **Access Control** - - Controlled reflection surface - - Explicit registration required - - Member visibility respect - -2. **Type Safety** - - Strong type checking - - Argument validation - - Return type verification - -3. **Isolate Safety** - - Controlled isolate access - - Error propagation - - Resource cleanup - ## Best Practices -1. **Registration** +1. **Early Registration** ```dart - // Register early void main() { - registerTypes(); + registerReflectableTypes(); runApp(); } ``` -2. **Metadata Usage** +2. **Caching Mirrors** ```dart - // Cache metadata - final metadata = Reflector.getTypeMetadata(User); - final properties = metadata.properties; - final methods = metadata.methods; + class UserService { + final Map _mirrors = {}; + + InstanceMirror getMirror(User user) { + return _mirrors.putIfAbsent(user, () => reflector.reflect(user)); + } + } ``` -3. **Error Handling** +3. **Comprehensive Error Handling** ```dart - // Comprehensive error handling try { - final result = mirror.invoke(name, args); + final result = mirror.invoke(const Symbol('method'), args); } on ReflectionException catch (e) { - handleError(e); + handleReflectionError(e); } ``` -4. **Isolate Management** - ```dart - // Proper cleanup - final isolate = IsolateMirrorImpl.other(...); - try { - await doWork(isolate); - } finally { - await isolate.kill(); - } - ``` - -This document provides a comprehensive overview of the Platform Reflection library's capabilities. For detailed API documentation, see the [API Reference](../README.md#api-reference). +This document provides an overview of the Platform Reflection library's capabilities. For detailed API documentation, please refer to the [API Reference](../README.md#api-reference). diff --git a/incubation/reflection/doc/index.md b/incubation/reflection/doc/index.md index a278906..4e70521 100644 --- a/incubation/reflection/doc/index.md +++ b/incubation/reflection/doc/index.md @@ -1,7 +1,7 @@ # Platform Reflection Documentation ## Overview -Platform Reflection is a modern reflection system for Dart that provides runtime type introspection and manipulation capabilities across all platforms. +Platform Reflection is a modern reflection system for Dart that provides runtime type introspection and manipulation capabilities across all platforms, including VM, Web, and Flutter. ## Documentation Structure @@ -21,19 +21,17 @@ Platform Reflection is a modern reflection system for Dart that provides runtime 1. Basic Usage - [Installation](../README.md#installation) - [Basic Reflection](quick_start.md#basic-usage) - - [Property Access](quick_start.md#2-property-access) - - [Method Invocation](quick_start.md#3-method-invocation) + - [Property Access and Method Invocation](quick_start.md#2-use-reflection) + - [Type Information](quick_start.md#3-type-information) 2. Advanced Usage - - [Type Information](quick_start.md#5-type-information) - - [Error Handling](quick_start.md#6-error-handling) - - [Common Patterns](quick_start.md#common-patterns) + - [Error Handling](quick_start.md#error-handling) - [Best Practices](quick_start.md#best-practices) + - [Performance Tips](quick_start.md#performance-tips) 3. Performance - [Optimization Techniques](technical_specification.md#performance-optimizations) - - [Performance Tips](quick_start.md#performance-tips) - - [Memory Management](technical_specification.md#memory-management) + - [Performance Considerations](capabilities.md#performance-considerations) ### Implementation Status @@ -45,23 +43,19 @@ Platform Reflection is a modern reflection system for Dart that provides runtime ✅ Type introspection ✅ Basic metadata support ✅ Error handling -✅ Cross-platform support +✅ Cross-platform support (VM, Web, Flutter) #### Known Limitations -❌ No cross-isolate reflection ❌ Limited generic support -❌ No source location tracking ❌ No extension method support -❌ No mixin composition ❌ Limited metadata capabilities ❌ No dynamic proxy generation -❌ No attribute-based reflection ### Development 1. Contributing - - [Getting Started](roadmap.md#getting-started) - [Priority Areas](roadmap.md#priority-areas) + - [Getting Started](roadmap.md#getting-started) - [Development Process](roadmap.md#development-process) 2. Future Plans @@ -77,9 +71,7 @@ Platform Reflection is a modern reflection system for Dart that provides runtime - [Performance Tips](quick_start.md#performance-tips) 2. Version Support - - [Support Matrix](roadmap.md#version-support-matrix) - [Breaking Changes](roadmap.md#breaking-changes) - - [Migration Support](roadmap.md#migration-support) ## Quick Links @@ -93,13 +85,12 @@ Platform Reflection is a modern reflection system for Dart that provides runtime 1. Review the [Technical Specification](technical_specification.md) 2. Check the [Development Roadmap](roadmap.md) 3. See [Priority Areas](roadmap.md#priority-areas) -4. Read [Contributing Guidelines](../CONTRIBUTING.md) +4. Read Contributing Guidelines (../CONTRIBUTING.md) ### For Framework Developers 1. Study the [Mirrors Comparison](mirrors_comparison.md) 2. Review [Implementation Details](technical_specification.md#implementation-details) -3. Check [Framework Integration](roadmap.md#framework-integration) -4. See [Enterprise Features](roadmap.md#enterprise-features) +3. Check [Framework Integration](roadmap.md#2-framework-integration) ## Document Updates diff --git a/incubation/reflection/doc/mirrors_comparison.md b/incubation/reflection/doc/mirrors_comparison.md index 2933552..daa1e3c 100644 --- a/incubation/reflection/doc/mirrors_comparison.md +++ b/incubation/reflection/doc/mirrors_comparison.md @@ -1,41 +1,21 @@ # Dart Mirrors vs Platform Reflection Comparison +This document compares our Platform Reflection library with Dart's built-in `dart:mirrors` package, highlighting key differences, trade-offs, and migration paths. + ## Core Features Comparison | Feature | dart:mirrors | Platform Reflection | Notes | -|---------|-------------|-------------------|--------| -| **Library Reflection** | -| Top-level functions | ✅ Full | ✅ Full | Complete parity | -| Top-level variables | ✅ Full | ✅ Full | Complete parity | -| Library dependencies | ✅ Full | ✅ Full | Complete parity | -| URI resolution | ✅ Full | ✅ Full | Complete parity | +|---------|--------------|---------------------|-------| +| Class Reflection | ✅ Full | ✅ Full | Requires registration in Platform Reflection | +| Method Invocation | ✅ Full | ✅ Full | Complete parity | +| Property Access | ✅ Full | ✅ Full | Complete parity | +| Constructor Invocation | ✅ Full | ✅ Full | Requires registration in Platform Reflection | +| Type Information | ✅ Full | ✅ Full | Complete parity | +| Metadata | ✅ Full | ⚠️ Limited | Basic metadata support in Platform Reflection | +| Generic Types | ✅ Full | ⚠️ Limited | Basic generic support in Platform Reflection | +| AOT Compilation | ❌ No | ✅ Yes | Platform Reflection supports AOT compilation | -| Feature | dart:mirrors | Platform Reflection | Notes | -|---------|-------------|-------------------|--------| -| **Isolate Support** | -| Current isolate | ✅ Full | ✅ Full | Complete parity | -| Other isolates | ✅ Full | ✅ Full | Complete parity | -| Isolate control | ✅ Full | ✅ Full | Pause/Resume/Kill | -| Error handling | ✅ Full | ✅ Full | Error/Exit listeners | - -| Feature | dart:mirrors | Platform Reflection | Notes | -|---------|-------------|-------------------|--------| -| **Type System** | -| Special types | ✅ Full | ✅ Full | void/dynamic/never | -| Type relationships | ✅ Full | ✅ Full | Complete type checking | -| Generic types | ✅ Full | ⚠️ Limited | Basic generic support | -| Type parameters | ✅ Full | ⚠️ Limited | Basic parameter support | - -| Feature | dart:mirrors | Platform Reflection | Notes | -|---------|-------------|-------------------|--------| -| **Metadata System** | -| Class metadata | ✅ Full | ✅ Full | Complete parity | -| Method metadata | ✅ Full | ✅ Full | Complete parity | -| Property metadata | ✅ Full | ✅ Full | Complete parity | -| Parameter metadata | ✅ Full | ✅ Full | Complete parity | -| Custom attributes | ✅ Full | ✅ Full | Complete parity | - -## Implementation Differences +## Key Implementation Differences ### Registration System @@ -53,55 +33,34 @@ class MyClass {} Reflector.register(MyClass); Reflector.registerProperty(MyClass, 'prop', String); Reflector.registerMethod(MyClass, 'method', [int]); +Reflector.registerConstructor(MyClass, '', parameterTypes: []); ``` -### Library Access +### Reflection Usage ```dart // dart:mirrors -final lib = MirrorSystem.findLibrary('my_lib'); +import 'dart:mirrors'; + +final instance = MyClass(); +final mirror = reflect(instance); +final value = mirror.getField(#prop).reflectee; +mirror.invoke(#method, [42]); // Platform Reflection -final lib = LibraryMirrorImpl.withDeclarations( - name: 'my_lib', - uri: Uri.parse('package:my_package/my_lib.dart'), -); -``` +import 'package:platform_reflection/mirrors.dart'; -### Isolate Handling - -```dart -// dart:mirrors -final mirror = reflect(isolate); -await mirror.invoke(#method, []); - -// Platform Reflection -final mirror = IsolateMirrorImpl.other(isolate, 'name', lib); -mirror.addErrorListener((error, stack) { - // Handle error -}); -``` - -### Type System - -```dart -// dart:mirrors -final type = reflectType(MyClass); -final isSubtype = type.isSubtypeOf(otherType); - -// Platform Reflection -final type = TypeMetadata( - type: MyClass, - name: 'MyClass', - // ... -); -final isSubtype = type.supertype == otherType; +final reflector = RuntimeReflector.instance; +final instance = reflector.createInstance(MyClass, positionalArgs: []) as MyClass; +final mirror = reflector.reflect(instance); +final value = mirror.getField(const Symbol('prop')).reflectee; +mirror.invoke(const Symbol('method'), [42]); ``` ## Performance Characteristics | Aspect | dart:mirrors | Platform Reflection | Winner | -|--------|-------------|-------------------|---------| +|--------|--------------|---------------------|--------| | Startup time | ❌ Slower | ✅ Faster | Platform Reflection | | Runtime performance | ❌ Slower | ✅ Faster | Platform Reflection | | Memory usage | ❌ Higher | ✅ Lower | Platform Reflection | @@ -110,7 +69,7 @@ final isSubtype = type.supertype == otherType; ## Platform Support | Platform | dart:mirrors | Platform Reflection | Winner | -|----------|-------------|-------------------|---------| +|----------|--------------|---------------------|--------| | VM | ✅ Yes | ✅ Yes | Tie | | Web | ❌ No | ✅ Yes | Platform Reflection | | Flutter | ❌ No | ✅ Yes | Platform Reflection | @@ -119,91 +78,84 @@ final isSubtype = type.supertype == otherType; ## Use Cases | Use Case | dart:mirrors | Platform Reflection | Better Choice | -|----------|-------------|-------------------|---------------| -| Dependency injection | ✅ Simpler | ⚠️ More setup | dart:mirrors | -| Serialization | ✅ Simpler | ⚠️ More setup | dart:mirrors | +|----------|--------------|---------------------|---------------| +| Dependency injection | ✅ Simpler | ⚠️ More setup | Depends on platform needs | +| Serialization | ✅ Simpler | ⚠️ More setup | Depends on platform needs | | Testing/Mocking | ✅ More flexible | ✅ More controlled | Depends on needs | | Production apps | ❌ Limited platforms | ✅ All platforms | Platform Reflection | ## Migration Path -### From dart:mirrors +To migrate from dart:mirrors to Platform Reflection: -1. Add registration: -```dart -// Before -@reflectable -class MyClass {} +1. Replace imports: + ```dart + // Before + import 'dart:mirrors'; + + // After + import 'package:platform_reflection/mirrors.dart'; + ``` -// After -@reflectable -class MyClass {} +2. Add registration for each reflectable class: + ```dart + void registerReflectables() { + Reflector.register(MyClass); + Reflector.registerProperty(MyClass, 'prop', String); + Reflector.registerMethod(MyClass, 'method', [int]); + Reflector.registerConstructor(MyClass, '', parameterTypes: []); + } + ``` -void register() { - Reflector.register(MyClass); - // Register members... -} -``` +3. Update reflection calls: + ```dart + // Before + final mirror = reflect(instance); + final value = mirror.getField(#prop).reflectee; -2. Update reflection calls: -```dart -// Before -final mirror = reflect(instance); -final value = mirror.getField(#prop); + // After + final reflector = RuntimeReflector.instance; + final mirror = reflector.reflect(instance); + final value = mirror.getField(const Symbol('prop')).reflectee; + ``` -// After -final mirror = reflector.reflect(instance); -final value = mirror.getField(const Symbol('prop')); -``` +4. Replace MirrorSystem usage: + ```dart + // Before + final classMirror = reflectClass(MyClass); -3. Handle libraries: -```dart -// Before -final lib = MirrorSystem.findLibrary('my_lib'); + // After + final classMirror = RuntimeReflector.instance.reflectClass(MyClass); + ``` -// After -final lib = LibraryMirrorImpl.withDeclarations( - name: 'my_lib', - uri: uri, -); -``` +5. Update your build process to ensure registration functions are called at startup. ## Trade-offs ### Advantages of Platform Reflection -1. Works everywhere -2. Better performance -3. Smaller code size -4. Better tree shaking -5. Full isolate support -6. Production-ready +1. Works on all platforms (VM, Web, Flutter, AOT) +2. Better performance and smaller code size +3. Supports AOT compilation +4. More controlled reflection surface ### Advantages of dart:mirrors 1. No registration needed -2. Simpler API -3. More dynamic capabilities -4. Better for development tools -5. More flexible +2. More dynamic capabilities +3. Simpler API for some use cases +4. Better for certain development tools ## Conclusion -Platform Reflection offers a more production-ready alternative to dart:mirrors with: -- Full cross-platform support -- Better performance characteristics -- More controlled reflection surface -- Full isolate support -- Production-ready features - -The main trade-off is the need for explicit registration, but this brings benefits in terms of performance, code size, and tree shaking. +Platform Reflection offers a production-ready alternative to dart:mirrors with cross-platform support, better performance, and AOT compilation compatibility. The main trade-off is the need for explicit registration, which provides more control but requires more setup. Choose Platform Reflection when: -- You need cross-platform support -- Performance is critical -- Code size matters -- You want production-ready reflection +- You need cross-platform or AOT compilation support +- Performance and code size are critical +- You want more control over the reflection surface -Choose dart:mirrors when: -- You're only targeting the VM -- Development time is critical -- You need maximum flexibility -- You're building development tools +Consider dart:mirrors when: +- You're only targeting the Dart VM +- You need maximum runtime flexibility +- You're building certain types of development tools + +Remember, the choice between Platform Reflection and dart:mirrors often comes down to your specific platform requirements and performance needs. diff --git a/incubation/reflection/doc/quick_start.md b/incubation/reflection/doc/quick_start.md index 6c6003e..ac71e7d 100644 --- a/incubation/reflection/doc/quick_start.md +++ b/incubation/reflection/doc/quick_start.md @@ -1,369 +1,110 @@ # Platform Reflection Quick Start Guide -This guide covers the most common use cases for Platform Reflection to help you get started quickly. +This guide covers the essential steps to get started with Platform Reflection, a drop-in replacement for dart:mirrors with AOT compilation support. ## Installation +Add this to your package's `pubspec.yaml` file: + ```yaml dependencies: platform_reflection: ^0.1.0 ``` +## Key Concepts + +1. **Explicit Registration**: Unlike dart:mirrors, Platform Reflection requires explicit registration of classes and their members. +2. **AOT Compilation Support**: The registration process enables AOT compilation, which dart:mirrors doesn't support. +3. **API Similarity**: The reflection API is similar to dart:mirrors, easing the transition. + ## Basic Usage -### 1. Simple Class Reflection +### 1. Define and Register a Class ```dart -import 'package:platform_reflection/reflection.dart'; +import 'package:platform_reflection/mirrors.dart'; -// 1. Define your class @reflectable class User { String name; int age; - + User(this.name, this.age); - - void birthday() => age++; + + String greet() => "Hello, $name!"; } -// 2. Register for reflection -void main() { - // Register class +void registerUser() { Reflector.register(User); - - // Register properties Reflector.registerProperty(User, 'name', String); Reflector.registerProperty(User, 'age', int); - - // Register methods - Reflector.registerMethod( - User, - 'birthday', - [], - true, - ); - - // Register constructor + Reflector.registerMethod(User, 'greet', [], false); Reflector.registerConstructor( User, '', parameterTypes: [String, int], parameterNames: ['name', 'age'], - creator: (String name, int age) => User(name, age), ); +} + +void main() { + registerUser(); + // Your application code here +} +``` + +### 2. Use Reflection + +```dart +void demonstrateReflection() { + final reflector = RuntimeReflector.instance; - // Use reflection + // Create instance final user = reflector.createInstance( User, - positionalArgs: ['John', 30], + positionalArgs: ['John Doe', 30], ) as User; + // Get mirror final mirror = reflector.reflect(user); - print(mirror.getField(const Symbol('name')).reflectee); // John - mirror.invoke(const Symbol('birthday'), []); - print(mirror.getField(const Symbol('age')).reflectee); // 31 -} -``` - -### 2. Property Access - -```dart -// Get property value -final mirror = reflector.reflect(instance); -final name = mirror.getField(const Symbol('name')).reflectee as String; - -// Set property value -mirror.setField(const Symbol('name'), 'Jane'); - -// Check if property exists -final metadata = Reflector.getPropertyMetadata(User); -if (metadata?.containsKey('name') ?? false) { - // Property exists -} -``` - -### 3. Method Invocation - -```dart -// Invoke method without arguments -mirror.invoke(const Symbol('birthday'), []); - -// Invoke method with arguments -final result = mirror.invoke( - const Symbol('greet'), - ['Hello'], -).reflectee as String; - -// Invoke method with named arguments -final result = mirror.invoke( - const Symbol('update'), - [], - {const Symbol('value'): 42}, -).reflectee; -``` - -### 4. Constructor Usage - -```dart -// Default constructor -final instance = reflector.createInstance( - User, - positionalArgs: ['John', 30], -) as User; - -// Named constructor -final instance = reflector.createInstance( - User, - constructorName: 'guest', -) as User; - -// Constructor with named arguments -final instance = reflector.createInstance( - User, - positionalArgs: ['John'], - namedArgs: {const Symbol('age'): 30}, -) as User; -``` - -### 5. Type Information - -```dart -// Get type metadata -final metadata = Reflector.getTypeMetadata(User); - -// Check properties -for (var property in metadata.properties.values) { - print('${property.name}: ${property.type}'); -} - -// Check methods -for (var method in metadata.methods.values) { - print('${method.name}(${method.parameterTypes.join(', ')})'); -} -``` - -### 6. Error Handling - -```dart -try { - // Attempt reflection - final mirror = reflector.reflect(instance); - mirror.invoke(const Symbol('method'), []); -} on NotReflectableException catch (e) { - print('Type not registered: $e'); -} on MemberNotFoundException catch (e) { - print('Member not found: $e'); -} on InvalidArgumentsException catch (e) { - print('Invalid arguments: $e'); -} on ReflectionException catch (e) { - print('Reflection error: $e'); -} -``` - -## Common Patterns - -### 1. Registration Helper - -```dart -void registerType(Type type) { - Reflector.register(type); - final scanner = Scanner(); - final metadata = scanner.scanType(type); + // Property access and modification + print('Name: ${mirror.getField(const Symbol('name')).reflectee}'); + mirror.setField(const Symbol('age'), 31); - // Register properties - for (var property in metadata.properties.values) { - Reflector.registerProperty( - type, - property.name, - property.type, - isWritable: property.isWritable, - ); - } + // Method invocation + final greeting = mirror.invoke(const Symbol('greet'), []).reflectee as String; + print(greeting); - // Register methods - for (var method in metadata.methods.values) { - Reflector.registerMethod( - type, - method.name, - method.parameterTypes, - method.returnsVoid, - parameterNames: method.parameters.map((p) => p.name).toList(), - isRequired: method.parameters.map((p) => p.isRequired).toList(), - ); - } + // Type information + final classMirror = reflector.reflectClass(User); + print('Type name: ${classMirror.name}'); } ``` -### 2. Property Observer +## Key Differences from dart:mirrors -```dart -class PropertyObserver { - final InstanceMirror mirror; - final Symbol propertyName; - final void Function(dynamic oldValue, dynamic newValue) onChange; - - PropertyObserver(this.mirror, this.propertyName, this.onChange); - - void observe() { - var lastValue = mirror.getField(propertyName).reflectee; - - Timer.periodic(Duration(milliseconds: 100), (_) { - final currentValue = mirror.getField(propertyName).reflectee; - if (currentValue != lastValue) { - onChange(lastValue, currentValue); - lastValue = currentValue; - } - }); - } -} -``` - -### 3. Method Interceptor - -```dart -class MethodInterceptor { - final InstanceMirror mirror; - final Symbol methodName; - final void Function(List args, Map named) beforeInvoke; - final void Function(dynamic result) afterInvoke; - - MethodInterceptor( - this.mirror, - this.methodName, - {this.beforeInvoke = _noOp, - this.afterInvoke = _noOp}); - - static void _noOp([dynamic _]) {} - - dynamic invoke(List args, [Map? named]) { - beforeInvoke(args, named ?? {}); - final result = mirror.invoke(methodName, args, named).reflectee; - afterInvoke(result); - return result; - } -} -``` +1. **Registration**: You must register classes, properties, methods, and constructors explicitly. +2. **Reflector Class**: Use the `Reflector` class for registration and the `RuntimeReflector` for reflection operations. +3. **Limited Automatic Discovery**: There's no automatic discovery of classes or members; everything must be registered. ## Best Practices -1. **Register Early** - ```dart - void main() { - // Register all types at startup - registerType(); - registerType(); - registerType(); - - // Start application - runApp(); - } - ``` +1. Register all reflectable types at application startup. +2. Cache instance mirrors for repeated operations on the same object. +3. Always handle potential `ReflectionException`s in your code. +4. Use reflection judiciously, as it can impact performance. -2. **Cache Mirrors** - ```dart - class UserService { - final Map _mirrors = {}; - - InstanceMirror getMirror(User user) { - return _mirrors.putIfAbsent( - user, - () => reflector.reflect(user), - ); - } - } - ``` +## Common Pitfalls -3. **Handle Errors** - ```dart - T reflectSafely(Function() operation, T defaultValue) { - try { - return operation() as T; - } on ReflectionException catch (e) { - print('Reflection failed: $e'); - return defaultValue; - } - } - ``` - -4. **Validate Registration** - ```dart - bool isFullyRegistered(Type type) { - final metadata = Reflector.getTypeMetadata(type); - if (metadata == null) return false; - - // Check properties - if (metadata.properties.isEmpty) return false; - - // Check methods - if (metadata.methods.isEmpty) return false; - - // Check constructors - if (metadata.constructors.isEmpty) return false; - - return true; - } - ``` - -## Common Issues - -1. **Type Not Registered** - ```dart - // Wrong - reflector.reflect(unregisteredInstance); - - // Right - Reflector.register(UnregisteredType); - reflector.reflect(instance); - ``` - -2. **Missing Property/Method Registration** - ```dart - // Wrong - Reflector.register(User); - - // Right - Reflector.register(User); - Reflector.registerProperty(User, 'name', String); - Reflector.registerMethod(User, 'greet', [String]); - ``` - -3. **Wrong Argument Types** - ```dart - // Wrong - mirror.invoke(const Symbol('greet'), [42]); - - // Right - mirror.invoke(const Symbol('greet'), ['Hello']); - ``` - -## Performance Tips - -1. **Cache Metadata** - ```dart - final metadata = Reflector.getTypeMetadata(User); - final properties = metadata.properties; - final methods = metadata.methods; - ``` - -2. **Reuse Mirrors** - ```dart - final mirror = reflector.reflect(instance); - // Reuse mirror for multiple operations - ``` - -3. **Batch Registration** - ```dart - void registerAll() { - for (var type in types) { - registerType(type); - } - } - ``` +1. Forgetting to register a class or its members before reflection. +2. Attempting to reflect on private members (not supported). +3. Not handling potential exceptions during reflection operations. ## Next Steps -- Read the [Technical Specification](technical_specification.md) for detailed implementation information -- Check the [API Reference](../README.md#api-reference) for complete API documentation -- See the [Mirrors Comparison](mirrors_comparison.md) for differences from dart:mirrors +- Review the [API Reference](../README.md#api-reference) for detailed information. +- Explore the [examples](../example) directory for more complex scenarios. +- If migrating from dart:mirrors, check the [Migration Guide](mirrors_comparison.md) for a detailed comparison and transition tips. + +Remember, Platform Reflection aims to provide the power of reflection with the benefits of AOT compilation. The trade-off is the need for explicit registration, which gives you more control over what can be reflected upon in your application. diff --git a/incubation/reflection/doc/roadmap.md b/incubation/reflection/doc/roadmap.md index 8f012c8..d6f0733 100644 --- a/incubation/reflection/doc/roadmap.md +++ b/incubation/reflection/doc/roadmap.md @@ -1,294 +1,175 @@ # Platform Reflection Roadmap -This document outlines the planned improvements and future direction of the Platform Reflection library. +This document outlines the current status, planned improvements, and future direction of the Platform Reflection library. ## Current Status (v0.1.0) ### Implemented Features -✅ Basic reflection system -✅ Property access/mutation +✅ Core reflection system with explicit registration +✅ Property access and mutation ✅ Method invocation ✅ Constructor handling ✅ Type introspection ✅ Basic metadata support -✅ Error handling -✅ Cross-platform support +✅ Comprehensive error handling +✅ Cross-platform support (VM, Web, Flutter, AOT) +✅ Basic generic type support +✅ Library reflection ### Known Limitations -❌ No cross-isolate reflection -❌ Limited generic support -❌ No source location tracking +❌ Limited support for complex generic types ❌ No extension method support -❌ No mixin composition ❌ Limited metadata capabilities ❌ No dynamic proxy generation -❌ No attribute-based reflection +❌ No reflection on private members ## Short-term Goals (v0.2.0) ### 1. Enhanced Generic Support -- [ ] Better generic type handling -- [ ] Generic type argument preservation -- [ ] Generic method support -- [ ] Generic constructor support -- [ ] Type parameter constraints +- [ ] Improved handling of complex generic types +- [ ] Support for generic methods and constructors +- [ ] Type parameter bounds and variance ### 2. Improved Type System -- [ ] Better type relationship checking -- [ ] Variance handling -- [ ] Type erasure handling -- [ ] Generic type instantiation -- [ ] Type parameter bounds +- [ ] Enhanced type relationship checking +- [ ] Better support for interfaces and mixins +- [ ] Improved handling of type aliases ### 3. Metadata Enhancements -- [ ] Rich metadata API -- [ ] Metadata inheritance -- [ ] Custom metadata providers -- [ ] Metadata validation -- [ ] Compile-time metadata +- [ ] Rich metadata API for custom annotations +- [ ] Improved retrieval and manipulation of metadata ### 4. Performance Optimizations -- [ ] Faster lookup mechanisms -- [ ] Better memory usage -- [ ] Optimized registration -- [ ] Improved caching -- [ ] Reduced startup time +- [ ] Further optimized lookup mechanisms +- [ ] Enhanced caching strategies +- [ ] Benchmarking and performance tuning ## Medium-term Goals (v0.3.0) -### 1. Dynamic Features -- [ ] Dynamic proxy generation -- [ ] Method interception -- [ ] Property interception -- [ ] Dynamic interface implementation -- [ ] Runtime mixin application +### 1. Advanced Type Features +- [ ] Support for extension methods +- [ ] Improved mixin composition handling +- [ ] Better support for sealed classes and enums -### 2. Advanced Type Features -- [ ] Extension method support -- [ ] Operator overloading -- [ ] Mixin composition -- [ ] Type alias support -- [ ] Named constructor factories +### 2. Framework Integration +- [ ] Deeper Flutter integration +- [ ] Built-in support for common serialization formats (JSON, protobuf) +- [ ] Integration with popular state management solutions -### 3. Tooling Support -- [ ] VS Code extension -- [ ] Dart analyzer plugin -- [ ] Documentation generator -- [ ] Migration tools -- [ ] Debug tools - -### 4. Framework Integration -- [ ] Flutter integration -- [ ] Built Value integration -- [ ] JSON serialization -- [ ] Database mapping -- [ ] Dependency injection +### 3. Tooling and Developer Experience +- [ ] VS Code extension for easier registration and usage +- [ ] Dart analyzer plugin for static analysis +- [ ] Code generation tools to automate registration ## Long-term Goals (v1.0.0) -### 1. Advanced Reflection -- [ ] Cross-isolate reflection -- [ ] Source location tracking -- [ ] Dynamic loading -- [ ] Code generation -- [ ] Hot reload support +### 1. Advanced Reflection Capabilities +- [ ] Dynamic proxy generation +- [ ] Method interception and AOP-like features +- [ ] Limited support for reflecting on private members (with security considerations) -### 2. Language Features -- [ ] Pattern matching -- [ ] Records support -- [ ] Sealed classes -- [ ] Enhanced enums -- [ ] Extension types +### 2. Language Feature Parity +- [ ] Full support for all Dart language features +- [ ] Reflection capabilities for upcoming Dart features -### 3. Enterprise Features -- [ ] Aspect-oriented programming -- [ ] Dependency injection -- [ ] Object-relational mapping -- [ ] Serialization framework -- [ ] Validation framework - -### 4. Security Features -- [ ] Access control -- [ ] Reflection policies -- [ ] Sandboxing -- [ ] Audit logging -- [ ] Security annotations +### 3. Enterprise and Framework Features +- [ ] Built-in dependency injection framework +- [ ] Advanced validation and serialization capabilities +- [ ] Integration with popular backend frameworks ## Implementation Priorities -### Phase 1: Foundation (Current) -1. Core reflection system -2. Basic type support -3. Essential operations -4. Error handling -5. Documentation +### Phase 1: Stabilization and Enhancement (Current) +1. Improve generic type support +2. Enhance performance and optimize caching +3. Expand test coverage +4. Improve documentation and examples -### Phase 2: Enhancement (Next) -1. Generic support -2. Type system improvements -3. Metadata enhancements -4. Performance optimizations -5. Framework integration +### Phase 2: Advanced Features and Integrations +1. Implement advanced type system features +2. Develop framework integrations +3. Create developer tools and plugins +4. Enhance metadata capabilities -### Phase 3: Advanced Features -1. Dynamic capabilities -2. Language feature support -3. Tooling integration -4. Security features -5. Enterprise features +### Phase 3: Towards 1.0 +1. Implement dynamic capabilities (proxies, interception) +2. Ensure full language feature support +3. Develop enterprise-level features +4. Final API stabilization and performance tuning ## Breaking Changes -### Planned for v0.2.0 -- API refinements for generic support -- Enhanced metadata system -- Improved type handling -- Registration system updates +### Potential for v0.2.0 +- API refinements for improved generic support +- Enhancements to the registration process for better type information -### Planned for v0.3.0 -- Dynamic proxy API -- Advanced type features -- Framework integration APIs -- Security system +### Potential for v0.3.0 +- Changes to support advanced type features +- Modifications to accommodate deeper framework integrations -### Planned for v1.0.0 -- Stable API finalization -- Enterprise feature integration -- Cross-isolate capabilities -- Advanced language features +### For v1.0.0 +- Final API stabilization +- Any necessary changes to support full language feature parity -## Migration Support +## Community Feedback Focus -### For Each Major Version -- Migration guides -- Breaking change documentation -- Upgrade tools -- Code modification scripts -- Support period - -## Community Feedback Areas - -### Current Focus -1. Generic type handling -2. Performance optimization -3. Framework integration -4. API usability -5. Documentation quality - -### Future Considerations -1. Enterprise features -2. Security requirements -3. Framework support -4. Language feature support -5. Tool integration +1. Generic type handling and edge cases +2. Performance in real-world scenarios +3. Integration pain points with popular frameworks +4. API ergonomics and ease of use +5. Documentation clarity and completeness ## Development Process -### 1. Feature Development -```mermaid -graph LR - A[Proposal] --> B[Design] - B --> C[Implementation] - C --> D[Testing] - D --> E[Documentation] - E --> F[Release] -``` +### Feature Development Workflow +1. Community proposal and discussion +2. Design and API draft +3. Implementation and internal testing +4. Community feedback and iteration +5. Documentation and example creation +6. Release and announcement -### 2. Release Cycle -- Major versions: Significant features/breaking changes -- Minor versions: New features/non-breaking changes -- Patch versions: Bug fixes/performance improvements +### Release Cycle +- Major versions: Significant features/breaking changes (roughly annually) +- Minor versions: New features/non-breaking changes (every 2-3 months) +- Patch versions: Bug fixes/performance improvements (as needed) -### 3. Testing Strategy -- Unit tests -- Integration tests -- Performance tests -- Platform compatibility tests -- Framework integration tests +### Testing Strategy +- Comprehensive unit test suite +- Integration tests with popular frameworks +- Performance benchmarks against dart:mirrors and direct code +- Cross-platform compatibility tests ## Contributing -### Priority Areas -1. Generic type support -2. Performance improvements -3. Framework integration -4. Documentation -5. Testing +### Priority Areas for Contribution +1. Generic type edge cases and improvements +2. Performance optimizations and benchmarks +3. Framework integration examples and utilities +4. Documentation improvements and tutorials +5. Test coverage expansion -### Getting Started -1. Review current limitations -2. Check roadmap priorities -3. Read contribution guidelines -4. Submit proposals -5. Implement features +### Getting Started with Contributions +1. Review the current limitations and roadmap +2. Check the issue tracker for "good first issue" labels +3. Read the CONTRIBUTING.md guidelines +4. Engage in discussions on open issues or create a new one +5. Submit pull requests with improvements or new features -## Support - -### Long-term Support (LTS) -- v1.0.0 and later -- Security updates -- Critical bug fixes -- Performance improvements -- Documentation updates - -### Version Support Matrix -| Version | Status | Support Until | -|---------|---------|--------------| -| 0.1.x | Current | 6 months | -| 0.2.x | Planned | 1 year | -| 0.3.x | Planned | 1 year | -| 1.0.x | Planned | 2 years | - -## Success Metrics - -### Technical Metrics -- Performance benchmarks -- Memory usage -- API coverage -- Test coverage -- Documentation coverage - -### Community Metrics -- Adoption rate -- Issue resolution time -- Community contributions -- User satisfaction -- Framework adoption - -## Get Involved - -### Ways to Contribute -1. Submit bug reports -2. Propose features -3. Improve documentation -4. Add test cases -5. Implement features - -### Communication Channels -- GitHub Issues -- Pull Requests -- Discord Server -- Stack Overflow -- Email Support - -## Timeline +## Tentative Timeline ### 2024 Q1-Q2 -- Enhanced generic support -- Improved type system -- Performance optimizations -- Documentation improvements +- Release v0.2.0 with enhanced generic support and performance improvements +- Expand framework integration examples +- Implement initial tooling support ### 2024 Q3-Q4 -- Dynamic features -- Framework integration -- Tool support -- Security features +- Release v0.3.0 with advanced type features and deeper framework integrations +- Develop and release initial VS Code extension and analyzer plugin ### 2025 -- Cross-isolate reflection -- Enterprise features -- Language feature support -- 1.0.0 release +- Implement dynamic proxy generation and method interception +- Finalize API for 1.0.0 release +- Develop enterprise-level features and integrations -Note: This roadmap is subject to change based on community feedback and evolving requirements. +Note: This roadmap is subject to change based on community feedback, emerging requirements, and developments in the Dart ecosystem. diff --git a/incubation/reflection/doc/technical_specification.md b/incubation/reflection/doc/technical_specification.md index b64a52c..579c400 100644 --- a/incubation/reflection/doc/technical_specification.md +++ b/incubation/reflection/doc/technical_specification.md @@ -6,64 +6,71 @@ ```mermaid graph TD - A[Reflector] --> B[Scanner] - A --> C[RuntimeReflector] - B --> D[TypeAnalyzer] - C --> E[MirrorSystem] - E --> F[Mirrors] - F --> G[ClassMirror] - F --> H[InstanceMirror] - F --> I[MethodMirror] + A[Reflector] --> B[RuntimeReflector] + B --> C[MirrorSystem] + C --> D[Mirrors] + D --> E[ClassMirror] + D --> F[InstanceMirror] + D --> G[MethodMirror] + D --> H[VariableMirror] + D --> I[LibraryMirror] + D --> J[TypeMirror] ``` ### Component Responsibilities #### 1. Reflector -- Central registration point -- Metadata management +- Static class for central registration and metadata management - Type registration validation -- Cache management +- Metadata storage for properties, methods, and constructors ```dart class Reflector { - static final Map _typeCache; - static final Map> _propertyMetadata; - static final Map> _methodMetadata; - static final Map> _constructorMetadata; + static void register(Type type); + static void registerProperty(Type type, String name, Type propertyType, {bool isWritable = true}); + static void registerMethod(Type type, String name, List parameterTypes, bool returnsVoid); + static void registerConstructor(Type type, String name, {List? parameterTypes, List? parameterNames, List? isRequired, List? isNamed, Function? creator}); + static bool isReflectable(Type type); + static Map? getPropertyMetadata(Type type); + static Map? getMethodMetadata(Type type); + static List? getConstructorMetadata(Type type); } ``` -#### 2. Scanner -- Type analysis -- Metadata extraction -- Registration validation -- Type relationship analysis - -```dart -class Scanner { - static final Map _typeInfoCache; - - static TypeInfo analyze(Type type) { - // Analyze class structure - // Extract metadata - // Build type relationships - } -} -``` - -#### 3. RuntimeReflector -- Instance creation -- Method invocation -- Property access -- Type reflection +#### 2. RuntimeReflector +- Singleton class for runtime reflection operations +- Instance creation and manipulation +- Type and class reflection +- Library reflection ```dart class RuntimeReflector { - InstanceMirror reflect(Object object) { - // Create instance mirror - // Setup metadata access - // Configure invocation handling - } + static final RuntimeReflector instance = RuntimeReflector._(); + + InstanceMirror reflect(Object object); + ClassMirror reflectClass(Type type); + TypeMirror reflectType(Type type); + LibraryMirror reflectLibrary(Uri uri); + + InstanceMirror createInstance(Type type, {List? positionalArgs, Map? namedArgs, String? constructorName}); +} +``` + +#### 3. MirrorSystem +- Manages the overall reflection system +- Provides access to libraries and types +- Handles special types (dynamic, void, never) + +```dart +class MirrorSystem implements MirrorSystemContract { + static MirrorSystem get instance; + static MirrorSystem current(); + + Map get libraries; + LibraryMirrorContract findLibrary(Symbol libraryName); + ClassMirrorContract reflectClass(Type type); + TypeMirrorContract reflectType(Type type); + IsolateMirrorContract get isolate; } ``` @@ -77,8 +84,8 @@ class TypeMetadata { final Map properties; final Map methods; final List constructors; - final bool isAbstract; - final bool isEnum; + final TypeMetadata? supertype; + final List interfaces; } ``` @@ -89,8 +96,8 @@ class MethodMetadata { final List parameterTypes; final List parameters; final bool returnsVoid; + final Type returnType; final bool isStatic; - final bool isAbstract; } ``` @@ -101,7 +108,6 @@ class PropertyMetadata { final Type type; final bool isReadable; final bool isWritable; - final bool isStatic; } ``` @@ -112,20 +118,11 @@ class PropertyMetadata { 1. Type Registration ```dart static void register(Type type) { - // Validate type - if (_typeCache.containsKey(type)) return; - - // Create metadata - final metadata = TypeMetadata( - type: type, - name: type.toString(), - properties: {}, - methods: {}, - constructors: [], - ); - - // Cache metadata - _typeCache[type] = metadata; + _reflectableTypes.add(type); + _propertyMetadata.putIfAbsent(type, () => {}); + _methodMetadata.putIfAbsent(type, () => {}); + _constructorMetadata.putIfAbsent(type, () => []); + _instanceCreators.putIfAbsent(type, () => {}); } ``` @@ -138,23 +135,16 @@ static void registerProperty( bool isReadable = true, bool isWritable = true, }) { - // Validate type registration - if (!isRegistered(type)) { - throw NotReflectableException(type); - } - - // Create property metadata - final metadata = PropertyMetadata( - name: name, - type: propertyType, - isReadable: isReadable, - isWritable: isWritable, + registerPropertyMetadata( + type, + name, + PropertyMetadata( + name: name, + type: propertyType, + isReadable: isReadable, + isWritable: isWritable, + ), ); - - // Cache metadata - _propertyMetadata - .putIfAbsent(type, () => {}) - [name] = metadata; } ``` @@ -165,30 +155,13 @@ static void registerMethod( String name, List parameterTypes, bool returnsVoid, { + Type? returnType, List? parameterNames, List? isRequired, + List? isNamed, + bool isStatic = false, }) { - // Validate type registration - if (!isRegistered(type)) { - throw NotReflectableException(type); - } - - // Create method metadata - final metadata = MethodMetadata( - name: name, - parameterTypes: parameterTypes, - parameters: _createParameters( - parameterTypes, - parameterNames, - isRequired, - ), - returnsVoid: returnsVoid, - ); - - // Cache metadata - _methodMetadata - .putIfAbsent(type, () => {}) - [name] = metadata; + // Implementation details... } ``` @@ -201,203 +174,76 @@ InstanceMirror createInstance( Map? namedArgs, String? constructorName, }) { - // Get constructor metadata - final constructors = Reflector.getConstructorMetadata(type); - if (constructors == null) { - throw ReflectionException('No constructors found'); - } - - // Find matching constructor - final constructor = constructors.firstWhere( - (c) => c.name == (constructorName ?? ''), - orElse: () => throw ReflectionException('Constructor not found'), - ); - - // Validate arguments - _validateArguments( - constructor, - positionalArgs, - namedArgs, - ); - - // Create instance - final instance = constructor.creator!( - positionalArgs, - namedArgs, - ); - - // Return mirror - return InstanceMirror( - instance, - type, - ); + // Implementation details... } ``` ### Method Invocation ```dart -InstanceMirror invoke( - Symbol methodName, - List positionalArguments, [ - Map? namedArguments, -]) { - // Get method metadata - final method = _getMethodMetadata(methodName); - if (method == null) { - throw ReflectionException('Method not found'); - } - - // Validate arguments - _validateMethodArguments( - method, - positionalArguments, - namedArguments, - ); - - // Invoke method - final result = method.invoke( - instance, - positionalArguments, - namedArguments, - ); - - // Return result mirror - return InstanceMirror( - result, - result.runtimeType, - ); +InstanceMirror invoke(Symbol methodName, List positionalArguments, [Map? namedArguments]) { + // Implementation details... } ``` ## Performance Optimizations -### 1. Metadata Caching -- Type metadata cached on registration -- Method metadata cached on registration -- Property metadata cached on registration - -### 2. Lookup Optimization -- O(1) type lookup -- O(1) method lookup -- O(1) property lookup - -### 3. Memory Management -- Weak references for type cache -- Lazy initialization of metadata -- Minimal metadata storage +- Metadata caching on registration for fast lookup +- Use of HashMap for O(1) average case lookups +- Lazy initialization of certain components (e.g., special types in MirrorSystem) +- Reuse of mirrors for repeated operations on the same object ## Error Handling -### Exception Hierarchy ```dart -abstract class ReflectionException implements Exception { +class ReflectionException implements Exception { final String message; - final StackTrace? stackTrace; + ReflectionException(this.message); + @override + String toString() => 'ReflectionException: $message'; } class NotReflectableException extends ReflectionException { - final Type type; + NotReflectableException(Type type) : super('Type is not reflectable: $type'); } class InvalidArgumentsException extends ReflectionException { - final String memberName; - final Type type; -} - -class MemberNotFoundException extends ReflectionException { - final String memberName; - final Type type; + InvalidArgumentsException(String message, Type type) : super(message); } ``` -### Validation Points -1. Registration validation -2. Argument validation -3. Type validation -4. Access validation - ## Platform Considerations -### Web Support -- No dart:mirrors dependency -- Tree-shaking friendly -- Minimal runtime overhead - -### Flutter Support -- AOT compilation compatible -- No code generation required -- Performance optimized - -### Native Support -- Cross-platform compatible -- No platform-specific code -- Consistent behavior +- Full support for VM, Web, Flutter, and AOT compilation +- No use of dart:mirrors, ensuring cross-platform compatibility +- Explicit registration allows for better tree-shaking and smaller code size ## Limitations and Constraints -### Technical Limitations -1. No cross-isolate reflection -2. No source location support -3. Limited generic support -4. No extension method support - -### Design Decisions -1. Explicit registration required -2. No private member access -3. No dynamic loading -4. No proxy generation +- Explicit registration required for all reflectable types and members +- Limited support for complex generic types +- No reflection on private members +- No dynamic loading of code or types at runtime ## Future Considerations -### Planned Improvements -1. Enhanced generic support -2. Better type relationship handling -3. Improved metadata capabilities -4. Performance optimizations - -### Potential Features -1. Attribute-based reflection -2. Dynamic proxy generation -3. Enhanced type analysis -4. Improved error reporting +- Enhanced generic type support, including variance and type parameter bounds +- Improved metadata capabilities, including custom metadata providers +- Dynamic proxy generation for more advanced use cases +- Potential for code generation tools to automate registration process ## Security Considerations -### Access Control -- No private member access -- Controlled reflection surface -- Explicit registration required - -### Type Safety -- Strong type checking -- Runtime validation -- Safe method invocation +- No access to private members, maintaining encapsulation +- Controlled reflection surface through explicit registration +- Runtime type checking and validation during reflection operations ## Testing Strategy -### Unit Tests -1. Registration tests -2. Reflection tests -3. Error handling tests -4. Performance tests +- Comprehensive unit tests for all core components (Reflector, RuntimeReflector, MirrorSystem) +- Integration tests simulating real-world usage scenarios +- Performance benchmarks comparing against direct method calls and dart:mirrors (where applicable) +- Cross-platform tests ensuring consistent behavior across VM, Web, and Flutter +- Stress tests with large numbers of registered types and reflection operations -### Integration Tests -1. Platform compatibility -2. Framework integration -3. Real-world scenarios -4. Edge cases - -## Documentation Requirements - -### API Documentation -1. Public API documentation -2. Usage examples -3. Best practices -4. Migration guides - -### Technical Documentation -1. Architecture overview -2. Implementation details -3. Performance considerations -4. Security guidelines +This technical specification provides a detailed overview of the Platform Reflection library's architecture, implementation details, and key considerations. For API documentation and usage examples, please refer to the [README](../README.md) and [Quick Start Guide](quick_start.md). diff --git a/incubation/reflection/lib/src/mirrors/mirror_system.dart b/incubation/reflection/lib/src/mirrors/mirror_system.dart index d5198f1..2e1583e 100644 --- a/incubation/reflection/lib/src/mirrors/mirror_system.dart +++ b/incubation/reflection/lib/src/mirrors/mirror_system.dart @@ -310,17 +310,17 @@ class MirrorSystem implements MirrorSystemContract { } } -/// The current mirror system. -MirrorSystemContract currentMirrorSystem() => MirrorSystem.current(); +// /// The current mirror system. +// MirrorSystemContract currentMirrorSystem() => MirrorSystem.current(); -/// Reflects an instance. -InstanceMirrorContract reflect(Object reflectee) => - MirrorSystem.instance.reflect(reflectee); +// /// Reflects an instance. +// InstanceMirrorContract reflect(Object reflectee) => +// MirrorSystem.instance.reflect(reflectee); -/// Reflects a class. -ClassMirrorContract reflectClass(Type key) => - MirrorSystem.instance.reflectClass(key); +// /// Reflects a class. +// ClassMirrorContract reflectClass(Type key) => +// MirrorSystem.instance.reflectClass(key); -/// Reflects a type. -TypeMirrorContract reflectType(Type key) => - MirrorSystem.instance.reflectType(key); +// /// Reflects a type. +// TypeMirrorContract reflectType(Type key) => +// MirrorSystem.instance.reflectType(key);