This is an automated email from the ASF dual-hosted git repository. chaokunyang pushed a commit to branch main in repository https://gitbox.apache.org/repos/asf/fory-site.git
commit 4dbcc7c26693e019c2ab5afea8c93d04d301ea1b Author: chaokunyang <[email protected]> AuthorDate: Tue Jul 28 03:08:12 2026 +0000 🔄 synced local 'docs/guide/' with remote 'docs/guide/' --- docs/guide/dart/code-generation.md | 93 ++++++++++++++++++++++++++++++++- docs/guide/dart/external-types.md | 11 +++- docs/guide/dart/grpc-support.md | 4 +- docs/guide/dart/index.md | 10 +++- docs/guide/dart/schema-evolution.md | 23 ++++++++ docs/guide/dart/schema-metadata.md | 21 ++++++-- docs/guide/dart/supported-types.md | 18 ++++++- docs/guide/dart/troubleshooting.md | 56 +++++++++++++++++--- docs/guide/dart/type-registration.md | 12 +++++ docs/guide/dart/web-platform-support.md | 25 ++++++++- docs/guide/dart/xlang-serialization.md | 17 +++++- 11 files changed, 268 insertions(+), 22 deletions(-) diff --git a/docs/guide/dart/code-generation.md b/docs/guide/dart/code-generation.md index 01624e3007..63e5aee954 100644 --- a/docs/guide/dart/code-generation.md +++ b/docs/guide/dart/code-generation.md @@ -56,15 +56,101 @@ For a class owned by another library, define an [external structural serializer](external-types.md) with `@ForyStruct(target: ExternalType)`. +## Inherited Fields + +For an ordinary struct, Fory follows the concrete superclass and applied-mixin +storage chain. All non-static instance storage is flattened into the concrete +child's one generated schema, globally ordered with fields declared directly +on the child. Interfaces and abstract accessors do not add storage. + +Field annotations belong to the field declaration. In particular, +`@ForyField(ignore: true)` on the declaring field is the only way to omit +ordinary storage. Fory reports a generation error instead of silently omitting +a field that is inaccessible, hidden, unsupported, or cannot be reconstructed. + +| Inherited field | Requirement | +| --------------------------------------- | ------------------------------------------------------------------------- | +| Public field | No parent annotation; generated child code accesses it directly | +| Private field in the child's library | No parent annotation; the generated part accesses it directly | +| Private field in another Dart library | A public boundary in that declaring library uses `exposePrivateFields` | +| Field marked `@ForyField(ignore: true)` | Omitted from the schema; no access or construction requirement is checked | + +To expose private state from a library that owns a base class: + +```dart +// package:model_owner/base.dart +import 'package:fory/fory.dart'; + +part 'base.fory.dart'; + +@ForyStruct(exposePrivateFields: true) +abstract class AccountBase { + AccountBase(String tenantId) : _tenantId = tenantId; + + final String _tenantId; + + String get tenantId => _tenantId; +} +``` + +The consumer annotates only its concrete type: + +```dart +// lib/account.dart +import 'package:fory/fory.dart'; +import 'package:model_owner/base.dart'; + +part 'account.fory.dart'; + +@ForyStruct() +final class Account extends AccountBase { + Account(String tenantId) : super(tenantId); +} +``` + +`exposePrivateFields` defaults to `false` and authorizes only the generated +private-field access companion owned by that library. It does not control field +discovery or same-library private access. Placing it on `Account` cannot expose +private fields owned by `model_owner`. If a hierarchy contains private fields +from several libraries, each declaring library needs its own public opted-in +boundary. + +The child source must import the provider namespace without hiding the +generated companion. A barrel is valid when it re-exports both the public +boundary and the companion. Across packages, generate and publish the +provider's `.fory.dart` part before building a consumer. + +For example, a restrictive barrel for the model above must include both names: + +```dart +export 'base.dart' + show AccountBase, $AccountBaseForyFieldAccess; +``` + +Non-ignored `final` and `late final` fields require an identity-preserving path +from a parameter of the concrete child's selected generative constructor to +the exact field. Initializing formals, super formals, redirects, and direct +constructor initializers are supported. A parameter with the same name is not +proof if the constructor ignores or transforms it. Use +`@ForyField(ignore: true)` or a manual serializer when the object cannot be +reconstructed without custom logic. + +The concrete child is registered independently and owns the only serializer +for its flattened schema. Parent serializers are not nested or invoked. +Inherited reference annotations feed the existing reference behavior exactly +like fields declared directly on the child. + ## Step 2 — Run the Generator From the directory that contains your `pubspec.yaml`: ```bash -dart run build_runner build --delete-conflicting-outputs +dart run build_runner build ``` -This emits a `.fory.dart` file next to your source file. Re-run this command any time you add or rename annotated types. +This emits a `.fory.dart` file next to your source file. Re-run this command any +time you add or rename annotated types, change hierarchy storage, or change an +exposure boundary. ## Step 3 — Register and Use @@ -107,6 +193,9 @@ class Event { When using evolving structs, also assign stable field IDs with `@ForyField(id: ...)` before you ship your first payload — those IDs are how Fory matches fields after a schema change. +Inherited and direct fields share this one ID namespace. Do not reuse an ID in +another superclass, mixin, or child field. + ## Choosing Generated or Manual Serialization Use an [external structural serializer](external-types.md) when another diff --git a/docs/guide/dart/external-types.md b/docs/guide/dart/external-types.md index 38314a33bd..827c058e05 100644 --- a/docs/guide/dart/external-types.md +++ b/docs/guide/dart/external-types.md @@ -62,14 +62,21 @@ must declare each schema field as `late final` without an initializer. Each serialized field name and Dart type, including nullability and generic arguments, must exactly match an accessible getter on the target. -Public target fields count toward the graph-memory budget automatically. Use +The declaration's field list is the complete external schema. Fory does not +automatically add fields from the target, its superclass, or its mixins. You +may explicitly declare an accessible inherited target property just like any +other schema field. `exposePrivateFields` applies only to ordinary Dart +hierarchies and is invalid with `ForyStruct.target`. + +Public target fields count toward the graph-memory budget automatically, but +that accounting does not add them to the serialized schema. Use `@ForyField(ignore: true)` on an extra declaration field to count other storage without serializing it. Run the generator as usual: ```bash -dart run build_runner build --delete-conflicting-outputs +dart run build_runner build ``` ## Register and Use the Target diff --git a/docs/guide/dart/grpc-support.md b/docs/guide/dart/grpc-support.md index 43f2a3a17e..58f77a2a13 100644 --- a/docs/guide/dart/grpc-support.md +++ b/docs/guide/dart/grpc-support.md @@ -78,7 +78,7 @@ Then run `build_runner` once to emit the Fory serializer part file for the generated models (this step is required before the code can run): ```bash -dart run build_runner build --delete-conflicting-outputs +dart run build_runner build ``` For this schema, the Dart generator emits (the model file and module are named @@ -281,7 +281,7 @@ grpc-dart APIs, but `fory` intentionally does not depend on gRPC. ### Generated Code References a Missing `.fory.dart` Part -Run `dart run build_runner build --delete-conflicting-outputs` after generating +Run `dart run build_runner build` after generating or regenerating the Dart sources. The serializer part file is produced by `build_runner`, not by `foryc`. diff --git a/docs/guide/dart/index.md b/docs/guide/dart/index.md index 8c201f6ab3..8097bc48ed 100644 --- a/docs/guide/dart/index.md +++ b/docs/guide/dart/index.md @@ -29,6 +29,7 @@ languages. - **Xlang**: serialize in Dart, deserialize in Java, Go, C#, and more without writing any glue code - **Platform support**: use the same generated-serializer API on Dart VM/AOT, Flutter, and web - **Fast**: generated serializer code replaces reflection during serialization +- **Inheritance**: ordinary structs flatten concrete superclass and mixin storage into one schema - **Schema evolution**: add or remove fields without breaking existing messages - **Circular references**: optional reference tracking handles shared or recursive object graphs - **Escape hatch**: write a manual serializer for any type that cannot be annotated @@ -106,17 +107,24 @@ void main() { Generate the companion file before running the program: ```bash -dart run build_runner build --delete-conflicting-outputs +dart run build_runner build ``` `PersonForyModule` is generated by `build_runner`. The `name` value is how peers in other languages identify the same type; keep it stable once your service is in production. Use `.` inside `name` to add a namespace prefix. +An ordinary annotated class includes its concrete superclass and applied-mixin +storage. Public and same-library private inherited fields need no parent +annotation. See [Code Generation](code-generation.md) for cross-library private +fields and constructor requirements. + ## API Overview - `Fory(...)` — create a serializer instance; create once and reuse it - `fory.serialize(value)` — returns `Uint8List` bytes - `fory.deserialize<T>(bytes)` — returns a `T` - `@ForyStruct()` — marks a class for code generation +- `@ForyStruct(exposePrivateFields: true)` — lets another library's generated + child serializer access private state owned by this library - `@ForyStruct(target: Type)` — generates an external structural serializer - `@ForyField(...)` — per-field options and canonical `type:` overrides - `@ListField(...)`, `@SetField(...)`, `@MapField(...)` — container sugar for nested `type:` trees diff --git a/docs/guide/dart/schema-evolution.md b/docs/guide/dart/schema-evolution.md index 6239dc45c3..741bf9cefe 100644 --- a/docs/guide/dart/schema-evolution.md +++ b/docs/guide/dart/schema-evolution.md @@ -62,6 +62,11 @@ class UserProfile { If you add field IDs after payloads are already in production, existing stored messages won't have them and evolution won't work correctly. +For an ordinary inherited struct, the concrete child's schema contains every +non-ignored field from its superclass and applied-mixin storage chain. Assign +IDs across that complete flattened hierarchy; an ID used by a parent or mixin +cannot be reused by the child. + For an [external structural serializer](external-types.md), the local serializer declaration supplies the evolving schema and each declaration field must match the corresponding target property. @@ -83,6 +88,9 @@ must match the corresponding target property. values exactly. - Change the registration identity (`id` or `name`) of a type after messages are in production. - Change a field's logical meaning without changing its ID. +- Introduce field hiding that leaves both an ancestor and child storage slot; + generation rejects this shape because both slots cannot be addressed + faithfully. ## Xlang Notes @@ -102,6 +110,21 @@ Use `compatible: false` only when every reader and writer always uses the same s final fory = Fory(compatible: false); ``` +## Regenerating Inherited Schemas + +Regenerate every affected `.fory.dart` part after adding inherited storage, +changing a superclass or mixin, or changing `exposePrivateFields`. Generate a +dependency package's provider part before building its consumers. + +Older Dart generated code did not include ordinary inherited fields. After +regeneration, compatible schemas use their normal missing-field and +unknown-field behavior. Fixed schemas written without the inherited fields are +not compatible with the corrected flattened schema; Fory does not add a +special legacy reader for those payloads. + +This migration changes generated field discovery only. It does not change the +runtime reference protocol. + ## Related Topics - [Configuration](configuration.md) diff --git a/docs/guide/dart/schema-metadata.md b/docs/guide/dart/schema-metadata.md index 9d189ffa85..61f93c522f 100644 --- a/docs/guide/dart/schema-metadata.md +++ b/docs/guide/dart/schema-metadata.md @@ -21,6 +21,10 @@ license: | Add `@ForyField(...)` to a field inside a `@ForyStruct()` class to change how that field is serialized. +For ordinary inheritance, metadata stays with the storage declaration and is +applied when any concrete annotated child discovers that field. A child +redeclaration does not replace or merge the ancestor field's metadata. + The same annotations apply to fields in an [external structural serializer declaration](external-types.md). @@ -38,10 +42,12 @@ The same annotations apply to fields in an ## `ignore` -Exclude a field from serialization entirely. Useful for cached, computed, or -UI-only values that should not land in a persisted or transmitted message. The -field still contributes to graph-memory accounting; because it has no wire -representation, do not combine `ignore` with other `ForyField` options. +Exclude the declaring field from serialization entirely. This is the only +supported way to omit ordinary instance storage, including inherited storage. +Useful examples include cached, computed, or UI-only values that should not +land in a persisted or transmitted message. The field still contributes to +graph-memory accounting; because it has no wire representation, do not combine +`ignore` with other `ForyField` options. ```dart @ForyField(ignore: true) @@ -59,6 +65,9 @@ String name = ''; Once a payload is shared across services, never reuse an `id` for a different field. +An ordinary child has one flattened field namespace. IDs must therefore be +unique across its child, superclass, and applied-mixin declarations. + ## `nullable` Explicitly marks a field as nullable or non-nullable, overriding what Fory infers from the Dart type. Use this when the Dart type is non-nullable but you want Fory to accept `null` on the wire (e.g., reading messages from an older producer that can omit the field). @@ -81,6 +90,10 @@ List<Object?> sharedNodes = <Object?>[]; Note: scalar types like `int`, `double`, and `bool` never benefit from reference tracking even if `ref: true` is set. +An inherited `ref` annotation behaves exactly like the same annotation on a +field declared directly by the concrete child. Inheritance does not introduce +another reference-tracking mode or owner. + ## `dynamic` Controls whether Fory writes the concrete type of the field value into the payload. diff --git a/docs/guide/dart/supported-types.md b/docs/guide/dart/supported-types.md index 55f3858b86..6af5f93777 100644 --- a/docs/guide/dart/supported-types.md +++ b/docs/guide/dart/supported-types.md @@ -130,11 +130,27 @@ class User { } ``` +Ordinary annotated classes may extend classes and apply mixins. Fory includes +every concrete instance storage field from that hierarchy in one child schema, +including inherited generic fields after specialization. Public fields and +private fields in the child's Dart library are accessed directly. +Cross-library private storage is supported only when its declaring library +provides a public boundary annotated with +`@ForyStruct(exposePrivateFields: true)`. + +Abstract getters, interfaces, static members, and other declarations without +instance storage are not fields. A real non-ignored storage field must have a +supported type, an unambiguous access path, and a valid reconstruction path; +otherwise generation fails. In particular, each `final` or `late final` field +must receive the decoded value unchanged through the concrete child's +constructor chain. + See [Code Generation](code-generation.md). Classes owned by another library can use an [external structural serializer](external-types.md) when their public fields -and construction match a local Fory schema declaration. +and construction match a local Fory schema declaration. External declarations +list their schema fields explicitly and do not scan the target hierarchy. ## Collections diff --git a/docs/guide/dart/troubleshooting.md b/docs/guide/dart/troubleshooting.md index fba1ef59bf..5e184fe8d6 100644 --- a/docs/guide/dart/troubleshooting.md +++ b/docs/guide/dart/troubleshooting.md @@ -33,7 +33,7 @@ The writer is sending a native-mode payload. Make sure every peer writes the xla Fory does not know how to serialize or deserialize this type. Fix it by: -1. Running code generation if you haven't: `dart run build_runner build --delete-conflicting-outputs` +1. Running code generation if you haven't: `dart run build_runner build` 2. Calling the generated `register` function (or `registerSerializer`) for the type **before** calling `serialize` or `deserialize`. 3. Registering **all** types that appear in a message, not just the root type. For example, if `Order` contains an `Address`, register both. @@ -42,11 +42,55 @@ Fory does not know how to serialize or deserialize this type. Fix it by: Regenerate code: ```bash -cd dart/packages/fory -dart run build_runner build --delete-conflicting-outputs +dart run build_runner build ``` -If you moved files or renamed types, rebuild before re-running analysis or tests. +Run the command from the package that owns the source. If a dependency exposes +private hierarchy fields, generate that provider package first and ensure its +published source contains the generated `.fory.dart` part, then regenerate the +consumer. If you moved files, renamed types, or changed a hierarchy, rebuild +before re-running analysis or tests. + +## Inherited private field is not accessible + +Ordinary hierarchy discovery includes private storage even when it is declared +in another Dart library. Privacy affects generated access, not whether the +field exists in the schema. + +- A private field declared in the same library as the child needs no parent + annotation. +- For a private field declared in another library, annotate a public hierarchy + boundary in that declaring library with + `@ForyStruct(exposePrivateFields: true)`. +- Import that provider directly, or use a barrel that re-exports both the + public boundary and its generated `$<Boundary>ForyFieldAccess` companion. +- If several libraries declare private fields in the hierarchy, each library + must provide its own boundary. + +Putting `exposePrivateFields: true` only on the consumer child cannot authorize +another library's private state. To omit a field intentionally, place +`@ForyField(ignore: true)` on its declaration. Fory does not silently omit an +inaccessible inherited field. + +## Final inherited field cannot be reconstructed + +A non-ignored `final` or `late final` field must receive its decoded value +unchanged from a parameter of the concrete child's selected generative +constructor. Fory can follow initializing formals, super formals, redirects, +and direct constructor initializers across the hierarchy. + +A parameter with the same name and type is insufficient if it is unused or its +value is cast, transformed, or passed through a function. Forward the decoded +value directly to the exact field, mark the field declaration with +`@ForyField(ignore: true)`, or use a manual serializer. + +## Inherited field is hidden + +A subclass field or accessor can hide an ancestor storage slot while both +physical slots remain on the object. Fory rejects this shape instead of +choosing one slot and losing the other. Rename or remove the hiding member, +ignore the ancestor field at its declaration when omission is intentional, or +use a manual serializer. ## External target generation fails @@ -141,7 +185,7 @@ matrix and platform guidance. Main Dart package: ```bash -dart run build_runner build --delete-conflicting-outputs +dart run build_runner build dart analyze dart test ``` @@ -150,7 +194,7 @@ Integration test package: ```bash cd dart/packages/fory-test -dart run build_runner build --delete-conflicting-outputs +dart run build_runner build dart test ``` diff --git a/docs/guide/dart/type-registration.md b/docs/guide/dart/type-registration.md index 7948e7afae..0a2f6bcae4 100644 --- a/docs/guide/dart/type-registration.md +++ b/docs/guide/dart/type-registration.md @@ -65,6 +65,16 @@ Call the generated `register` function from the `.fory.dart` file. It installs a UserModelsForyModule.register(fory, User, id: 100); ``` +For an ordinary inherited type, register the concrete annotated child. Its +generated serializer already owns the complete flattened child schema; Fory +does not require runtime registration of a superclass or mixin merely because +it contributes fields. + +Register an independently annotated concrete parent only when values whose +runtime type is that parent are also serialized. A provider-only +`@ForyStruct(exposePrivateFields: true)` boundary supplies generated field +access and has no registration entry of its own. + External structural serializers use the same generated registration API. Pass the external target type: @@ -97,6 +107,8 @@ See [Manual Serializers](custom-serializers.md) for how to implement a serialize - Register **before** the first `serialize` or `deserialize` call. - Register **every** class that can appear in a message, not only the root type. +- Do not register generated private-field access companions; register only + concrete serialized types. - Keep IDs (or names) **stable** once payloads are persisted or exchanged across services. Changing them will break deserialization of old messages. - Do not mix a numeric ID on one side with a name on the other for the same type. diff --git a/docs/guide/dart/web-platform-support.md b/docs/guide/dart/web-platform-support.md index f329be4d58..0d0190d272 100644 --- a/docs/guide/dart/web-platform-support.md +++ b/docs/guide/dart/web-platform-support.md @@ -36,6 +36,8 @@ Fory Dart supports: - Flutter web applications. - Generated `@ForyStruct` serializers and manually registered serializers on all supported targets. +- Ordinary generated inheritance, including typed cross-library private-field + companions. - External structural serializers generated with `@ForyStruct(target: ...)`. ## Code Generation Is Required @@ -75,13 +77,20 @@ Generate the companion file before building or testing: ```bash cd dart/packages/fory -dart run build_runner build --delete-conflicting-outputs +dart run build_runner build ``` The registration call is the same on VM/AOT, Flutter, and web. Manual serializers use `registerSerializer(...)`; generated structs use the generated `register` wrapper. +Inherited fields use the same statically generated code on every platform. +Public and same-library private fields are accessed directly. A provider +library annotated with `@ForyStruct(exposePrivateFields: true)` emits typed +static access methods for its own private state; it does not use mirrors, +callbacks, runtime member lookup, or a parent serializer. Generate a dependency +provider before compiling its consumer. + ## 64-Bit Integer Rules Dart VM `int` values are signed 64-bit values. Dart web `int` values are backed @@ -182,11 +191,23 @@ web: ```bash cd dart/packages/fory -dart run build_runner build --delete-conflicting-outputs +dart run build_runner build dart test dart test -p chrome ``` +For an application smoke test, also compile and execute the actual generated +entry point: + +```bash +dart compile js --fatal-warnings bin/app.dart -o build/app.js +node build/app.js +``` + +Use a model with the same hierarchy and imports as the production application +when validating cross-library private fields. Compilation alone does not prove +that registration and round-trip execution work. + If Chrome tests fail with a stale generated file or missing part file, rerun `build_runner` and then retry the test command from `dart/packages/fory`. diff --git a/docs/guide/dart/xlang-serialization.md b/docs/guide/dart/xlang-serialization.md index 639878b5d1..2bea4ca01e 100644 --- a/docs/guide/dart/xlang-serialization.md +++ b/docs/guide/dart/xlang-serialization.md @@ -83,7 +83,9 @@ ExternalSerializersForyModule.register( ``` The declaration's field IDs, names, nullability, and wire-width annotations -define the Dart-side xlang schema. +define the Dart-side xlang schema. An external declaration may explicitly list +an accessible inherited target property, but Fory does not automatically scan +the external target hierarchy. ## Dart to Java Example @@ -189,6 +191,17 @@ Fory matches fields by name or by stable field ID. For robust cross-language int 5. Use `Timestamp`, `LocalDate`, and `Duration` for temporal fields rather than raw `DateTime`. 6. Validate real round trips across all languages before shipping. +For an ordinary Dart class, Fory flattens concrete superclass and applied-mixin +storage into the annotated child's one struct schema. Parent and child fields +share one field-ID namespace and one canonical ordering, so the peer language +should define the equivalent flat field set. A parent is not encoded as a +nested object. + +Inherited `@ForyField(ref: true)` and nested container reference metadata use +the same reference behavior as fields declared directly on the child. +Inheritance does not change xlang reference framing or add parent-level +reference state. + ## Type Mapping Notes for Dart Because Dart `int` is not itself a promise about the exact xlang wire width, prefer explicit field metadata when exact cross-language interpretation matters: @@ -233,7 +246,7 @@ Before relying on a cross-language contract in production, test a payload end-to Run the Dart side: ```bash -dart run build_runner build --delete-conflicting-outputs +dart run build_runner build dart analyze dart test ``` --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
