Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions zorphy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -959,18 +959,18 @@ abstract class $Derived<T extends num> implements $$Base<T> {
Use `explicitSubTypes` to enable cross-type operations:

```dart
@Zorphy(explicitSubTypes: [$Dog, $Cat])
@Zorphy(generateJson: true, explicitSubTypes: [$Dog, $Cat])
abstract class $Pet {
String get name;
int get age;
}

@Zorphy()
@Zorphy(generateJson: true)
abstract class $Dog implements $Pet {
String get breed;
}

@Zorphy()
@Zorphy(generateJson: true)
abstract class $Cat implements $Pet {
double get whiskerLength;
}
Expand All @@ -986,6 +986,13 @@ final cat = dog.changeToCat(whiskerLength: 3.5);
// Cat(name: 'Buddy', age: 5, whiskerLength: 3.5)
```

A `changeTo` body converts by round-tripping through JSON, so it needs a JSON
surface to call: `generateJson: true` on every declared subtype, and on the base
too whenever the base is not sealed — a base that is not sealed needs
`nonSealed: true` as well, or it has no `toJson()` for the switch's default case
to call. A hierarchy that does not generate JSON gets no `changeTo` methods
rather than methods that reference `toJson`/`fromJson` nobody emitted.

### 7. CompareTo Feature

Generate comparison methods showing differences between instances:
Expand Down
8 changes: 7 additions & 1 deletion zorphy/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,7 @@ abstract class $Account {
### Advanced: ChangeTo and CompareTo

```dart
@Zorphy(explicitSubTypes: [$Circle, $Rectangle])
@Zorphy(generateJson: true, explicitSubTypes: [$Circle, $Rectangle])
abstract class $$Shape {
String get name;
}
Expand All @@ -384,6 +384,12 @@ abstract class $$Shape {
final rectangle = circle.changeToRectangle(width: 10.0, height: 15.0);
```

`changeTo` converts by round-tripping through JSON, so it is generated only when
the classes it dispatches over generate JSON: `generateJson: true` on every
declared subtype, and on the base too whenever the base is not sealed — a base
that is not sealed needs `nonSealed: true` as well, or it has no `toJson()` for
the switch's default case to call.

```dart
@Zorphy(generateCompareTo: true, generateJson: true)
abstract class $Document {
Expand Down
10 changes: 10 additions & 0 deletions zorphy/lib/src/analysis/class_analyzer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,16 @@ class ClassAnalyzer {
return annot == null ? null : ConstantReader(annot);
}

/// Whether [element]'s own `@Zorphy`/`@Zorphy2` annotation enables JSON
/// generation.
///
/// `generateJson` is opt-in in every preset and is NOT inherited (only
/// `typeKey` is), so every class in a hierarchy decides for itself. A
/// generator that emits a call to another class's `toJson()`/`fromJson()`
/// has to ask that class instead of assuming the call resolves.
static bool generatesJson(ClassElement element) =>
_readSubtypeAnnotation(element)?.peek('generateJson')?.boolValue ?? false;

/// Extract agent annotations (@AgentTool, @AgentRisk, @AgentInternal,
/// @AgentExclude, @AgentToolParam) from the class and its fields.
static AgentDirectiveInfo _extractAgentDirectiveInfo(
Expand Down
62 changes: 56 additions & 6 deletions zorphy/lib/src/generators/extension_generator.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'package:code_builder/code_builder.dart';

import '../analysis/class_analyzer.dart';
import '../ast/ast.dart';
import '../helpers.dart' as helpers;
import 'base_generator.dart';
Expand Down Expand Up @@ -69,15 +70,61 @@ class CompareToExtensionGenerator extends ConcreteClassGenerator {
/// Generates changeTo extension methods for explicit subtypes.
///
/// Produces a native [Extension] spec.
///
/// A `changeTo<Subtype>` body is a JSON round-trip: it collects the runtime
/// subtype's `toJson()`, overlays the patch's `toJson()`, and rebuilds the
/// target with `fromJson`. Those members exist only on a class generated with
/// `generateJson: true`, so the extension is withheld unless the JSON surface
/// it calls is really there (issue #159) — otherwise a hierarchy that never
/// asked for JSON gets a part file that does not compile.
class ChangeToExtensionGenerator extends UniversalGenerator {
ChangeToExtensionGenerator();

@override
bool shouldGenerate(GenerationContext context) {
return context.config.generateChangeTo &&
context.metadata.explicitSubtypes.isNotEmpty;
if (!context.config.generateChangeTo) return false;
final metadata = context.metadata;
if (metadata.explicitSubtypes.isEmpty) return false;
return _jsonSurfaceExists(context);
}

/// Whether every type the generated bodies call has a JSON surface.
///
/// The switch dispatches on the *runtime* subtype, so each declared subtype
/// needs its own `toJson()` and `fromJson`. A base that is not sealed also
/// needs its own `toJson()`, because its `switch` carries a
/// `_ => this.toJson()` default — see [_hasBaseCase].
bool _jsonSurfaceExists(GenerationContext context) {
final metadata = context.metadata;
if (!metadata.isSealed && !_hasBaseCase(context)) return false;
for (final subtype in metadata.explicitSubtypes) {
final element = metadata.allAnnotatedClasses[subtype.interfaceName];
// An unresolvable subtype is not evidence that its JSON surface exists.
if (element == null) return false;
if (!ClassAnalyzer.generatesJson(element)) return false;
}
return true;
}

/// Whether the generated `switch` carries a `_ => this.toJson()` default —
/// and the base declares the `toJson()` that default calls.
///
/// A `sealed` base needs no default: its switch is exhaustive over the
/// declared subtypes. Any other base is not — a plain `$` base, an undeclared
/// closure, or a subtype declared in another library (#142, where sealing is
/// deliberately withheld) — and its default calls `toJson()` on the base,
/// which `JsonGenerator` emits only for a `nonSealed` base. A base that
/// declares `explicitSubTypes` never gets one from `JsonExtensionGenerator`,
/// whose `shouldGenerate` skips any class that declares subtypes. So the
/// base case exists exactly when JSON is on AND the base is `nonSealed`.
///
/// The gate and the emitter both read this, so a base without a `toJson()`
/// can neither pass the gate nor get a default case that calls it.
static bool _hasBaseCase(GenerationContext context) =>
!context.metadata.isSealed &&
context.config.generateJson &&
context.metadata.nonSealed;

@override
List<Spec> generateSpec(GenerationContext context) {
final metadata = context.metadata;
Expand All @@ -91,7 +138,7 @@ class ChangeToExtensionGenerator extends UniversalGenerator {
sourceClassName: metadata.cleanName,
explicitSubTypes: metadata.explicitSubtypes,
knownClasses: knownClasses,
isSealed: metadata.isSealed,
baseCase: _hasBaseCase(context),
),
];
}
Expand All @@ -101,7 +148,7 @@ class ChangeToExtensionGenerator extends UniversalGenerator {
required String sourceClassName,
required List<dynamic> explicitSubTypes,
required List<String> knownClasses,
required bool isSealed,
required bool baseCase,
}) {
final sourceClassNameTrimmed = sourceClassName.replaceAll(r'\$', '');
final methods = <Method>[];
Expand Down Expand Up @@ -219,8 +266,11 @@ class ChangeToExtensionGenerator extends UniversalGenerator {
// For non-sealed polymorphic bases the base class itself is
// instantiable, so `switch (this)` over the base type must also cover
// the base case — otherwise the switch is non-exhaustive ("doesn't
// match 'X()'"). A wildcard default keeps it exhaustive.
if (!isSealed) {
// match 'X()'"). A wildcard default keeps it exhaustive. `shouldGenerate`
// has already refused the extension when that default would call a
// `toJson()` the base never declared, so this is the same predicate the
// gate reads, not a second guess at it.
if (baseCase) {
subtypeCases.add('_ => this.toJson()');
}
body.add('final _json = Map<String, dynamic>.from(');
Expand Down
Loading
Loading