Skip to content

fix: withhold changeTo when the JSON surface it calls is absent (#159) - #161

Merged
arrrrny merged 4 commits into
masterfrom
fix/issue-159
Nov 16, 2026
Merged

arrrrny merged 4 commits into
masterfrom
fix/issue-159

Conversation

@arrrrny

@arrrrny arrrrny commented Nov 16, 2026 •

Copy link
Copy Markdown
Owner

What was wrong

A sealed base with explicitSubTypes got a changeTo<Subtype> extension even when neither the base nor its subtypes enabled generateJson. That body converts by round-tripping through JSON:

final _json = Map<String, dynamic>.from(
  switch (this) {
    Circle circle => circle.toJson(),
    Square square => square.toJson(),
    _ => this.toJson(),
  },
);
_json.addAll(_patcher.toJson());
return Circle.fromJson(_json);

generateJson is opt-in in every preset, so on a default hierarchy none of those members exist and the generated part does not analyze — exactly the three diagnostics in the issue.

Root cause

ChangeToExtensionGenerator.shouldGenerate asked only for generateChangeTo + explicitSubTypes. It never asked whether the JSON surface its own body calls is actually generated. _patcher.toJson() is fine (PatchBase always has it); the subtype toJson()/fromJson() calls are not.

Fix

Gate the extension on the surface it calls (lib/src/generators/extension_generator.dart):

  • every declared subtype must generate JSON — the switch dispatches on the runtime subtype, so each declared subtype needs its own toJson() and fromJson();
  • a non-sealed base additionally needs its own JSON, because it is instantiable and its switch carries a _ => this.toJson() default;
  • a subtype whose element cannot be resolved counts as no evidence of a JSON surface, so the extension is withheld rather than guessed.

generateJson is opt-in in every preset and is not inherited (only typeKey is — see ClassAnalyzer._resolveInheritedTypeKey), so the check reads each subtype's own @Zorphy/@Zorphy2 annotation through the new ClassAnalyzer.generatesJson(element) helper instead of assuming the base's flag propagates.

This is deliberately the "base and/or subtypes" reading from the issue: a sealed base switches over its subtypes only, so a hierarchy where the subtypes carry JSON keeps changeTo even though the base itself does not.

Docs: README §6 and SKILL.md now show generateJson: true on the changeTo examples (and say why) — a JSON-less hierarchy correctly gets no changeTo methods.

Before / after

Reproduced on master with the real pipeline (resolved ClassElement → ClassAnalyzer → Orchestrator.generate) over the issue's exact shape, then re-analyzed:

sealed_no_json.zorphy.dart:1191: undefined_instance_member_read — The member 'toJson' isn't defined for the type 'Circle'.
sealed_no_json.zorphy.dart:1231: undefined_instance_member_read — The member 'toJson' isn't defined for the type 'Square'.
sealed_no_json.zorphy.dart:1304: undefined_static_member_read — The class 'Circle' doesn't have a static member or constructor named 'fromJson'.

After the fix that same fixture analyzes with zero diagnostics.

Test evidence

  • red: dart test -j 2 test/generation/issue_159_sealed_change_to_without_json_test.dart — Expected: empty / Actual: [undefined_instance_member_read … 'toJson' isn't defined for the type 'Circle', … undefined_static_member_read … 'fromJson'] (2 failing)
  • green: same command — 00:12 +6: All tests passed!
  • full suite: dart test -j 2 — 00:37 +360: All tests passed!
  • dart analyze lib → No issues found!; dart analyze (example, after build_runner) → No issues found!

New regression coverage pins three cases: no JSON anywhere (no changeTo, zero diagnostics), JSON on base + subtype (changeTo keeps its round-trip), and JSON on the subtypes only of a sealed base (changeTo preserved).

Note for #160

PR #160 (2.5.0) is still open and carries test/release/analyze_clean_gate_test.dart with a characterization test asserting this broken output. Once both land, that characterization test fails by design — _sealedNoJsonFixture moves into the strict zero-diagnostic group and the characterization test is deleted, per the issue comment. I left #160's branch untouched.

Closes #159

Summary by CodeRabbit

  • Bug Fixes

    • changeTo methods are now generated only when the required JSON support is available for the declared subtypes and, where applicable, the base type. This prevents generated code from referencing unavailable JSON methods.
    • Non-sealed base types now receive a changeTo fallback only when they support JSON conversion.
  • Documentation

    • Clarified the JSON generation requirements for changeTo methods, including the nonSealed setting for non-sealed base types.

A `changeTo<Subtype>` body converts by round-tripping through JSON: it
collects the runtime subtype's `toJson()`, overlays the patch's
`toJson()`, and rebuilds the target with `fromJson`.
`ChangeToExtensionGenerator` only asked for `generateChangeTo` +
`explicitSubTypes`, so a sealed base in a hierarchy that never opted into
JSON got a generated part calling `toJson`/`fromJson` nobody emitted —
the part file did not analyze.

Gate the extension on the surface its own body calls: every declared
subtype must generate JSON (the switch dispatches on the runtime subtype),
and a non-sealed base additionally needs its own, for the `_ => this.toJson()`
default. An unresolvable subtype counts as no evidence, so the extension is
withheld rather than guessed.

`generateJson` is opt-in in every preset and is not inherited, so the check
reads each subtype's own `@Zorphy`/`@Zorphy2` annotation through the new
`ClassAnalyzer.generatesJson`.

README and SKILL now show `generateJson: true` on the changeTo examples,
since a JSON-less hierarchy correctly gets no changeTo methods.
@coderabbitai

coderabbitai Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Caution

Review failed

The pull request is closed.

Walkthrough

The changeTo generator now checks for JSON support on declared subtypes and, when needed, the base class. Regression tests cover supported and unsupported hierarchies. The README and SKILL document the generation requirements.

Changes: changeTo JSON gating

Layer / File(s) Summary
Check JSON surfaces and build dispatch
zorphy/lib/src/analysis/class_analyzer.dart, zorphy/lib/src/generators/extension_generator.dart
The generator checks that each declared subtype resolves to a class with JSON generation enabled. For an unsealed base, it also requires JSON generation and nonSealed: true before emitting the default toJson() case.
Test supported and unsupported hierarchies
zorphy/test/generation/issue_159_sealed_change_to_without_json_test.dart, zorphy/test/release/analyze_clean_gate_test.dart
Regression tests cover hierarchies without JSON generation, JSON-enabled subtypes, and cross-library bases. The strict release fixture map now includes the sealed no-JSON case; its separate characterization test was removed.
Document JSON requirements
zorphy/README.md, zorphy/SKILL.md
The examples enable JSON generation. The documentation states the conditions for generating changeTo methods and the non-sealed base case.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix · Severity of issue fixed: Medium

Possibly related PRs

  • arrrrny/zorphy#160: Adds the release analyze-clean gate that this PR updates to check the changeTo generation behavior.
Merge Risk: Moderate · up to b5407

Generated changeTo code can still reference a missing toJson() when a JSON-enabled sealed intermediate subtype declares its own subtypes. The README example also uses a base without nonSealed, so the documented changeTo call is not generated. Fix both before merging.

- [ ] Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@zuraffa-review zuraffa-review Bot left a comment

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.

Review — #161 @ c5fd072

Verdict: 1 major, 2 minor. The core fix is right and the regression coverage is genuinely end-to-end (resolved ClassElement → ClassAnalyzer → Orchestrator, then the analyzer over the generated part) rather than a golden-string comparison. I verified it by driving the real pipeline over scratch fixtures:

  • sealed base, no JSON anywhere → changeTo withheld, 0 diagnostics
  • sealed base + generateJson: true → changeTo kept, 0 diagnostics
  • sealed base, JSON on the subtypes only → changeTo kept ("base and/or subtypes"), 0 diagnostics
  • mixed subtypes (one with JSON, one without) → changeTo withheld, 0 diagnostics
  • non-sealed base, no nonSealed: true → changeTo still emitted, and toJson is undefined on the base

Test evidence on this host: cd example && dart run build_runner build (the suite's fixtures need it — without that step 15 suites fail in setUpAll with Fixture not generated), then dart test -j 2 → 360 passed, including the 6 new cases.

Findings

  1. 🟠🎯 extension_generator.dart:99 — the base-side gate asks for generateJson, but a non-sealed base only has a toJson() when it is also nonSealed, so a cross-library hierarchy still emits a part file that does not compile. ⚡ effort. Repro inline.
  2. 🔵🧪 issue_159_..._test.dart:221 — _isMissingJsonMember narrows "zero diagnostics" to two codes; worth stating in the helper's doc comment. ⚡
  3. 🔵📐 README.md:991, SKILL.md:388 — the new doc note states a rule the code does not implement. ⚡

No security, stability or performance concerns: the change is ~30 lines of generator code that removes a class of compile failure, plus tests and docs.

/// 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).

}

/// The diagnostics #159 is about: a call to a JSON member the class never got.
bool _isMissingJsonMember(String diagnostic) =>

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 "zero diagnostics" assertion only looks at two diagnostic codes — effort ⚡

_isMissingJsonMember keeps every group green as long as no undefined_instance_member_read / undefined_static_member_read appears (asserted at lines 277, 330, 382). That is the right filter for #159 — those two codes are exactly what the issue reports — but the assertions read as "the generated library analyzes clean", a stronger claim than they make.

The distinction matters in this harness: _$CircleFromJson / _$CircleToJson come from json_serializable, which build.yaml runs after zorphy (runs_before: ["json_serializable:json_serializable"]), so a standalone Orchestrator pass legitimately leaves undefined_unqualified_name_read behind for those helpers. Without that context, a reader widening the fixtures will either chase a phantom or turn the filter into a false red.

Please record it where the next person will look:

/// The diagnostics #159 is about: a call to a JSON member the class never got.
///
/// Deliberately narrow. The part file also references `_$XFromJson` / `_$XToJson`,
/// which json_serializable emits in a LATER build step (build.yaml:
/// `runs_before: ["json_serializable:json_serializable"]`), so a whole-part
/// "no diagnostics at all" assertion is not available to a standalone
/// Orchestrator pass — widen this only for missing-JSON-member codes.
bool _isMissingJsonMember(String diagnostic) =>

Comment thread zorphy/README.md Outdated

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.

@zuraffa-review

Copy link
Copy Markdown
Contributor

Walkthrough — how this review was produced

Scope. arrrrny/zorphy#161 @ c5fd072 (head unchanged since the webhook fired; mergeable: MERGEABLE, mergeStateStatus: UNSTABLE, so no conflict resolution was needed). Reviewed the diff plus the surrounding generator context at the head ref — extension_generator.dart, class_analyzer.dart, json_generator.dart, generation_config.dart, class_graph.dart — and the preset table that decides when generateChangeTo is on at all (standard/full only, lean off; generateJson opt-in in every preset).

Method. Rather than reasoning about the emitter from the diff alone, I drove the real pipeline over throwaway fixtures (resolved ClassElement → ClassAnalyzer.analyze → Orchestrator.generate, then package:analyzer over the generated part) in a /tmp clone, covering five hierarchy shapes. That is what surfaced the non-sealed-base gap: the gate and the emitter disagree about when the base has a toJson() of its own.

Verified locally. cd example && dart run build_runner build → 178 outputs; dart test -j 2 → 04:5x +360: All tests passed!. Note for anyone reproducing: the suite needs the example/ fixtures generated first, or 15 suites fail in setUpAll with Fixture not generated — that is a missing build step, not a red tree.

Verdict. 1 major (🟠 extension_generator.dart:99), 2 minor (🔵 test-filter documentation, 🔵 README/SKILL note). The core fix — gating changeTo on the JSON surface its own body calls — is correct for every sealed shape, including the "subtypes only" reading the issue asks for, and the new regression test is real end-to-end coverage rather than a golden string. The major is the remaining gap: a base that is neither sealed nor nonSealed (a cross-library hierarchy is the common case) passes the gate and still emits a switch whose default calls a toJson() that base never declares.

Everything above is posted as zuraffa-review[bot] on the commit-pinned review; the three findings carry suggested diffs and a verified repro.

The base-side gate asked only for generateJson, but a base that is not
sealed gets a toJson() of its own only when it is also nonSealed: a base
declaring explicitSubTypes is skipped by JsonExtensionGenerator, and
JsonGenerator emits toJson() under `if (metadata.nonSealed)` alone. A
cross-library hierarchy (sealing withheld, #142) therefore passed the gate
and emitted a `_ => this.toJson()` default the base could not answer — the
same #159 compile failure in a new shape.

Both the gate and the emitter now read one `_hasBaseCase` predicate
(!isSealed && generateJson && nonSealed), so a base without a toJson() can
neither pass nor get a default case that calls it. New regression group
pins the cross-library pair; the test helper records why its
missing-JSON-member filter is narrow; README/SKILL state the corrected rule.
@arrrrny

arrrrny commented Nov 16, 2026

Copy link
Copy Markdown
Owner Author

Review-findings resolution

All three findings were valid against c5fd072 and are applied in 291fa1c.

Thread Verdict Notes
zorphy/lib/src/generators/extension_generator.dart:99 — base-side gate asks for generateJson, but a non-sealed base only declares toJson() when it is also nonSealed applied One predicate now drives both sides: _hasBaseCase(context) = !isSealed && generateJson && nonSealed. shouldGenerate refuses the extension when a non-sealed base has no toJson(), and the emitter adds the _ => this.toJson() default from the same value instead of re-deriving it from isSealed. Confirmed the two emitter conditions cited: JsonGenerator emits toJson() only under if (metadata.nonSealed), and JsonExtensionGenerator.shouldGenerate skips any class with explicitSubTypes.
zorphy/test/generation/issue_159_sealed_change_to_without_json_test.dart:221 — _isMissingJsonMember narrows "zero diagnostics" to two codes applied Doc comment records that the filter is deliberately narrow, and why a whole-part "no diagnostics at all" claim is unavailable to a standalone Orchestrator pass (json_serializable emits _$XFromJson/_$XToJson in a later build step).
zorphy/README.md:991, zorphy/SKILL.md:388 — the doc note states a rule the code does not implement applied Both now say: generateJson: true on every declared subtype, and on the base too whenever it 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.

Regression coverage added

A fourth group pins the exact shape the major finding reproduced — $$Shape in one library with explicitSubTypes: [$Circle], $Circle in a second library, generateJson: true on both:

  • red before the fix: cross_base.zorphy.dart: undefined_instance_member_read — The member 'toJson' isn't defined for the type 'Shape'.
  • green after: the base emits no changeTo extension and the two-library hierarchy analyzes with zero diagnostics.

Suite: dart test -j 2 → 363 passed (360 before, +3 new). dart analyze lib test/generation/issue_159_sealed_change_to_without_json_test.dart → no issues; dart format clean on every line this change adds.

Unrelated pre-existing note (not touched here): dart analyze at the zorphy/ package root exits 2 on pubspec.yaml:11 invalid_dependency — the zorphy_annotation path dependency restored in 58f07bc, this PR's parent.

#160 (zorphy 2.5.0) merged to master and added a characterization test in
test/release/analyze_clean_gate_test.dart that asserts the pre-fix #159
behavior (a sealed base without JSON still emits changeTo's toJson/fromJson
dispatch). This PR fixes #159, so that assertion now fails by design. Per the
test's own instructions, move the sealed_no_json fixture into the strict
zero-diagnostics group and delete the characterization test.

Also apply canonical dart format to the new issue #159 regression test, which
the format job flagged.
@arrrrny
arrrrny merged commit 853040e into master Nov 16, 2026
11 of 12 checks passed
@arrrrny

arrrrny commented Nov 16, 2026

Copy link
Copy Markdown
Owner Author

Merge task

merged as 853040e

CI was green (format, analyze, test, build_runner_smoke, migrator, analyzer_compat 13 & 14). While this task ran, #160 (zorphy 2.5.0) merged to master — I merged master in and reconciled the analyze-clean gate per #160's own instruction: the sealed_no_json fixture moved into the strict zero-diagnostics group and the #159 characterization test was removed. Linked issue #159 auto-closed on merge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Sealed base with explicitSubTypes emits subtype toJson/fromJson calls when generateJson is off (generated code does not compile)

1 participant