Repository navigation
fix: withhold changeTo when the JSON surface it calls is absent (#159) - #161
Conversation
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.
|
Caution Review failedThe pull request is closed. Walkthrough
Merge Risk:
|
There was a problem hiding this comment.
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 →
changeTowithheld, 0 diagnostics - sealed base +
generateJson: true→changeTokept, 0 diagnostics - sealed base, JSON on the subtypes only →
changeTokept ("base and/or subtypes"), 0 diagnostics - mixed subtypes (one with JSON, one without) →
changeTowithheld, 0 diagnostics - non-sealed base, no
nonSealed: true→changeTostill emitted, andtoJsonis 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
- 🟠🎯
extension_generator.dart:99— the base-side gate asks forgenerateJson, but a non-sealed base only has atoJson()when it is alsononSealed, so a cross-library hierarchy still emits a part file that does not compile. ⚡ effort. Repro inline. - 🔵🧪
issue_159_..._test.dart:221—_isMissingJsonMembernarrows "zero diagnostics" to two codes; worth stating in the helper's doc comment. ⚡ - 🔵📐
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; |
There was a problem hiding this comment.
🟠🎯 _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:
JsonGeneratoremits a polymorphic base'stoJson()only underif (metadata.nonSealed)(lib/src/generators/json_generator.dart:221);JsonExtensionGeneratorskips any class withexplicitSubTypes(json_generator.dart:546-549), so a base that declares subtypes never getstoJson()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) => |
There was a problem hiding this comment.
🔵🧪 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) =>|
|
||
| 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` |
There was a problem hiding this comment.
🔵📐 The new doc note states a rule the code does not implement — effort ⚡
A
changeTobody converts by round-tripping through JSON, so it needs a JSON surface to call: the classes generated withgenerateJson: 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.
Walkthrough — how this review was producedScope. Method. Rather than reasoning about the emitter from the diff alone, I drove the real pipeline over throwaway fixtures (resolved Verified locally. Verdict. 1 major (🟠 Everything above is posted as |
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.
Review-findings resolutionAll three findings were valid against
Regression coverage addedA fourth group pins the exact shape the major finding reproduced —
Suite: Unrelated pre-existing note (not touched here): |
#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.
Merge taskmerged 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 |
What was wrong
A sealed base with
explicitSubTypesgot achangeTo<Subtype>extension even when neither the base nor its subtypes enabledgenerateJson. That body converts by round-tripping through JSON:generateJsonis 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.shouldGenerateasked only forgenerateChangeTo+explicitSubTypes. It never asked whether the JSON surface its own body calls is actually generated._patcher.toJson()is fine (PatchBasealways has it); the subtypetoJson()/fromJson()calls are not.Fix
Gate the extension on the surface it calls (
lib/src/generators/extension_generator.dart):switchdispatches on the runtime subtype, so each declared subtype needs its owntoJson()andfromJson();switchcarries a_ => this.toJson()default;generateJsonis opt-in in every preset and is not inherited (onlytypeKeyis — seeClassAnalyzer._resolveInheritedTypeKey), so the check reads each subtype's own@Zorphy/@Zorphy2annotation through the newClassAnalyzer.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
changeToeven though the base itself does not.Docs: README §6 and SKILL.md now show
generateJson: trueon the changeTo examples (and say why) — a JSON-less hierarchy correctly gets nochangeTomethods.Before / after
Reproduced on
masterwith the real pipeline (resolvedClassElement→ClassAnalyzer→Orchestrator.generate) over the issue's exact shape, then re-analyzed:After the fix that same fixture analyzes with zero diagnostics.
Test evidence
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)00:12 +6: All tests passed!dart test -j 2—00:37 +360: All tests passed!dart analyze lib→No issues found!;dart analyze(example, afterbuild_runner) →No issues found!New regression coverage pins three cases: no JSON anywhere (no
changeTo, zero diagnostics), JSON on base + subtype (changeTokeeps its round-trip), and JSON on the subtypes only of a sealed base (changeTopreserved).Note for #160
PR #160 (2.5.0) is still open and carries
test/release/analyze_clean_gate_test.dartwith a characterization test asserting this broken output. Once both land, that characterization test fails by design —_sealedNoJsonFixturemoves 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
changeTomethods 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.changeTofallback only when they support JSON conversion.Documentation
changeTomethods, including thenonSealedsetting for non-sealed base types.