Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
11 changes: 8 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,11 @@ 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: the classes generated with `generateJson: true` (the base too,
unless it is sealed). A hierarchy that does not generate JSON gets no `changeTo`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵📐 The new doc note states a rule the code does not implement — effort ⚡

A changeTo body converts by round-tripping through JSON, so it needs a JSON surface to call: the classes generated with generateJson: true (the base too, unless it is sealed).

For a base that is neither sealed nor nonSealed, generateJson: true is not enough — such a base declares no toJson() of its own (see the inline finding on extension_generator.dart:99), so the parenthetical is wrong exactly where a reader would rely on it. Once the gate is fixed, something like:

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 non-sealed base 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.

The same sentence in SKILL.md:388 ("generateJson: true on the base, or on every declared subtype of a sealed base") needs the same qualifier.

methods rather than methods that reference `toJson`/`fromJson` nobody emitted.

### 7. CompareTo Feature

Generate comparison methods showing differences between instances:
Expand Down
6 changes: 5 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,10 @@ 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 the base,
or on every declared subtype of a sealed base).

```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
32 changes: 30 additions & 2 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,13 +70,40 @@ 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 non-sealed base is
/// instantiable itself, so its `switch` also carries a `_ => this.toJson()`
/// default that needs the base's own `toJson()`.
bool _jsonSurfaceExists(GenerationContext context) {
final metadata = context.metadata;
if (!metadata.isSealed && !context.config.generateJson) return false;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠🎯 _jsonSurfaceExists gates the base on generateJson, but the base only declares toJson() when it is also nonSealed — effort ⚡

The gate reads "a non-sealed base is instantiable, so its switch carries _ => this.toJson() and needs its own JSON", and tests context.config.generateJson. The emitter's default case is keyed on isSealed alone (extension_generator.dart:251-253). Those are not the same condition:

  • JsonGenerator emits a polymorphic base's toJson() only under if (metadata.nonSealed) (lib/src/generators/json_generator.dart:221);
  • JsonExtensionGenerator skips any class with explicitSubTypes (json_generator.dart:546-549), so a base that declares subtypes never gets toJson() from there either.

So a base that is not sealed and not nonSealed passes the gate with generateJson: true while having no toJson() at all — and the emitted switch calls it. That is #159's exact failure mode in the one hierarchy shape this fix does not cover. isSealed is also false for reasons other than nonSealed: true: a non-$$ base, an undeclared closure, or a declared subtype that lives in another library (the #142 cross-library case, where sealing is deliberately withheld).

Reproduced through the real pipeline — $$Shape in one library with @Zorphy(generateJson: true, explicitSubTypes: [$Circle]), $Circle in a second library with @Zorphy(generateJson: true):

shape.zorphy.dart: undefined_instance_member_read — The member 'toJson' isn't defined for the type 'Shape'.

Adding nonSealed: true to that same base makes the diagnostic disappear and the base declare its own toJson(), which confirms the predicate.

Suggested change — derive the gate and the emitter from ONE helper so they cannot drift:

  bool _jsonSurfaceExists(GenerationContext context) {
    final metadata = context.metadata;
    if (!metadata.isSealed && !_baseDeclaresToJson(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;
  }

  /// The base's own `toJson()` — the target of the `_ => this.toJson()` default
  /// case. A polymorphic base declares one only when JSON is on AND the base is
  /// `nonSealed` (json_generator.dart:221); a base with `explicitSubTypes` never
  /// gets one from JsonExtensionGenerator (json_generator.dart:546-549).
  bool _baseDeclaresToJson(GenerationContext context) =>
      context.config.generateJson && context.metadata.nonSealed;

then pass that same predicate into _buildChangeToExtension for the if (!isSealed) branch instead of re-deriving it from isSealed. A non-sealed base cannot be dispatched exhaustively without a default case, so withholding the extension is the only correct answer when it has no toJson() of its own — the fixture worth pinning is the cross-library pair above (or a $$ base with no nonSealed whose declared subtype lives abroad).

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;
}

@override
Expand Down
Loading
Loading