diff --git a/.claude/skills/msgbuf-workflow/SKILL.md b/.claude/skills/msgbuf-workflow/SKILL.md new file mode 100644 index 00000000..ebfb3529 --- /dev/null +++ b/.claude/skills/msgbuf-workflow/SKILL.md @@ -0,0 +1,257 @@ +--- +name: msgbuf-workflow +description: The working method for developing msgbuf — issue intake and triage, reproducing with a .proto first, sub-agent briefs, adversarial probe reviews composing generator features, the verification gate (Maven build, regenerated test sources as golden files, TypeScript golden files and tsc), branch/PR/commit discipline, and the wire-format and generated-code doctrines. Load at the start of any session doing feature or bug work on this repository. +--- + +# The msgbuf working method + +This skill is the meta-knowledge of how a session on this repository should run. It complements, +never duplicates, `CLAUDE.md` (build facts, architecture, gotchas) and `README.md` (the public +documentation of the `.proto` syntax, options and targets). Read both first. The GitHub issue +tracker at `msgbuf/msgbuf` **is** the work queue; `CHANGELOG.md` is the record of what shipped. + +## 1. The operating loop + +Work is a pipeline, not a pile: + +1. **Intake**: user reports (chat or GitHub issues) and the open issues at `msgbuf/msgbuf` + (`gh issue list -R msgbuf/msgbuf`). Bugs outrank queued features; a generator crash or + uncompilable generated code outranks everything. Triage every new issue with a diagnosis + comment *before* fixing. Labels are the GitHub defaults (`bug`, `enhancement`, `documentation`, …). +2. **Reproduce before dispatching.** Almost every report reduces to a `.proto` file. Write it, + run the built generator on it in a scratch directory, and compile or run the output: + + ```bash + J=$(ls $PWD/de.haumacher.msgbuf.generator/target/msgbuf-generator-*-full.jar) + java -jar $J -out /out /repro.proto # add -ts for the TypeScript target + ``` + + Know whether the problem is in the parser, the resolution/specialization stage, ID synthesis or + one code generator (§ "Generator Pipeline" in CLAUDE.md), and whether it is a real bug, an + already-fixed one, or your own probe error before an agent burns tokens. If the main tree is + agent-owned, reproduce in a git worktree (`git worktree add --detach /repro main`), + never in the live tree. +3. **Dispatch** one sub-agent per coherent package (§2), or do it yourself when the package is + small. msgbuf has one toolchain and one reactor, so parallel work needs separate worktrees (§3). +4. **Review with a novel probe** (§4). Non-negotiable. +5. **Gate** (§5), **commit and open or update the PR** (§6), and **merge it** once review and gate + are green (§6). Close the issue with the fixing commit or PR plus a summary comment naming the + regression test. +6. **Before finishing: `gh issue list -R msgbuf/msgbuf`.** Anything you find and defer becomes an + issue (like #16–#21, found while building the TypeScript target), so a crashed session loses + nothing. + +Track packages with TaskCreate/TaskUpdate; keep statuses honest (in_progress on dispatch, +completed only after the commit is pushed). + +## 2. Agent briefs — what makes them work + +Use Opus for generator and runtime packages; Sonnet only for mechanical chores (regenerating, +README tables). Run in background; you'll be notified. A good brief contains, in order: + +- **Grounding**: "Read CLAUDE.md and README.md. Study ." Name the module + (`de.haumacher.msgbuf` runtime, `de.haumacher.msgbuf.generator`, the Maven plugin) and whether + `ast/proto.proto` or `parser/protobuf.jj` is in scope — both have regeneration consequences (§5). +- **The task as design intent**, with the load-bearing decisions already made: what the wire + format carries, what the generated API looks like, which options (`NoInterfaces`, `NoJson`, + `SharedGraph`, …) the change must respect, what the generator rejects with an error instead of + emitting broken code. Quote the user's own words where they designed the feature. +- **User fixtures embedded verbatim**: the `.proto` from the report, the JSON the user expects, the + compiler error they got. They become the regression test. +- **Explicit acceptance tests**: which test package under `src/test/java/test/` gets the new + `.proto` and the JUnit 3 test (`extends TestCase`, see CLAUDE.md); JSON/binary/XML round-trips + (write → read → equal) for every format the options leave enabled; exact expected JSON strings + where the format is the point. +- **The build discipline block** (the point is not wasting runs, not avoiding them): + - The edit loop runs the **owning module's targeted test**: + `mvn -q -pl de.haumacher.msgbuf.generator -am test -Dtest=TestHierarchy -Dsurefire.failIfNoSpecifiedTests=false`. + `-am` is needed unless the current `msgbuf-api` SNAPSHOT is installed in `~/.m2`. + - A generator change is not tested until the checked-in test sources are regenerated (§5) — + they are compiled from the repository, not generated by the build. + - The full `mvn clean install` runs at the end, before the report. A run whose inputs did not + change is not repeated "to be sure". Batch independent lookups in one call. +- **The standing rules block**: ALL existing tests green; never hand-edit generated code + (regenerate it: test sources, the AST classes from `proto.proto`, the JavaCC parser); + generated code and `msgbuf-api` stay GWT-compatible (no `java.io` Reader/Writer, Java language + level of the root pom); do NOT commit; **nothing half-done — cut whole items only and report + every cut**; a new generator error message names the file, the definition and the fix. +- **Ask for a report**: mechanism chosen and why, alternatives rejected, cuts, which checked-in + generated files changed and why, test count before/after. A vague report predicts a vague delivery. + +**Reworks go back to the same agent** via SendMessage with the failing probe and the demand: +*fix it generally, not to the probe*. If several rework rounds fail, question the architecture, +not the tests. + +**Stalled agents**: if a background agent's transcript goes quiet, check for a running `mvn` or +`java` process first (a long build is not a stall), then nudge-resume via SendMessage ("Resume +exactly where you left off: "). If it stays frozen, take the remainder over; +its uncommitted work is usually further along than its last message suggests (`git status`, run +its tests before redoing anything). + +**Crash recovery**: the crashed session's transcript is +`~/.claude/projects/-home-haui-devel-msgbuf/.jsonl`, sub-agent transcripts are in +`/subagents/`. Pull the last `Agent` tool_use out of the session transcript (that is the +brief, verbatim), check the tree (`git status`, `mvn -q compile`), and re-dispatch with a resume +preamble stating what exists and what compiles. Check `gh issue list` — reports filed during the +crash are untriaged. + +## 3. Concurrency — the rules + +- **Never let two agents edit the same file.** When parallelizing, write an explicit FILE BOUNDARY + paragraph into *both* briefs ("do not touch X, Y, Z; if you must, STOP and report"). +- **Shared hot spots have one owner per round**: `MessageGenerator.java` (most features touch it), + `ast/proto.proto` (regenerates the AST every generator class uses), `parser/protobuf.jj` + (regenerates the parser), and the checked-in test sources (a regeneration rewrites many files). +- **Concurrent Maven runs in one tree collide** on `target/` and on the `~/.m2` install of the + same SNAPSHOT. A second agent gets its own worktree (`git worktree add -b + /wt-x main`, run from this repo) and uses `mvn verify`, never `install`, so it cannot + overwrite the artifacts the main tree builds against. +- A commit made while an agent has uncommitted work in the tree must be **selective** + (`git add `). +- **A merge is not gated by the commits it merges.** Run the full gate (§5) on the merged tree — + generated code and generator changes are exactly where merges break. + +## 4. The probe review (the quality mechanism) + +After a delivery reports done and before committing: **write a `.proto` the agent never saw**, +composing the new feature with existing ones: inheritance three levels deep with an abstract +intermediate, nested messages and enums, cross-file `import` and `extends`, `@Nullable`, +`repeated` and `map` of the new construct, reserved-word names in backticks, and the option +matrix (`NoInterfaces`, `NoJson`/`NoBinary`/`NoXml`, `NoReflection`, `NoListener`, `NoVisitor`, +`SharedGraph`, `OpenWorld`). Generate, compile, round-trip. Good probes ask "is the mechanism +general?" not "does the happy path work?". Keep passing probes as permanent test packages. + +**Expect your own probes to be wrong first.** The traps seen so far: + +- **The generator derives its output root from the `package` declaration** when `-out` is missing: + the test protos live in `test//` but declare `package test..data;`, so running the jar on + them without `-out` writes a stray `src/test/test/` tree. Always pass `-out`. +- **A run with `-Dmsgbuf.ts.update=true` is not a test run** — it rewrites the TypeScript golden + files and then passes by construction. Rerun without the flag, and review the golden diff. +- **`mvn -pl de.haumacher.msgbuf.generator` alone fails to resolve `msgbuf-api:…-SNAPSHOT`** unless it + is installed — use `-am`, and then `-Dsurefire.failIfNoSpecifiedTests=false` with `-Dtest=…`. +- **Stale jar**: `target/msgbuf-generator-*-full.jar` is whatever the last `install`/`package` built, + possibly on another branch. Rebuild before probing a change. +- **A green unit build does not cover the plugin integration test**: `-Prun-its` runs `simple-it`, + a consumer project that configures the plugin with the documented parameter names, generates and + compiles. The plugin testing harness (`MojoRule.lookupConfiguredMojo`) does not resolve parameter + aliases, so configuration names can only be tested there. +- **CLAUDE.md is not always right about the wire format**: polymorphic values are written as + `[typeId, {fields}]` (a two-element array whose second element is the object), and only when the + hierarchy root is abstract; references to a concrete type use `writeContent()` without a tag. + Check `MessageGenerator` (`writeTo`, `isMonomorphicReferenceToTypeInPolymorphicHierarchy`) + before asserting a format. +- **`gh pr view ` / `gh pr edit ` fail** with a GraphQL "Projects (classic) is being + deprecated" error. Use `gh pr view --json …` for reading and `gh api -X PATCH + repos/msgbuf/msgbuf/pulls/ -F body=@file` for editing. +- **`gh pr checkout` names the local branch differently** from the PR head, so a plain `git push` + is refused. Push with `git push origin HEAD:`. +- **A push can be rejected with a transient 403** ("Permission to msgbuf/msgbuf.git denied"). Report + it; on the user's request, retry once before suspecting credentials. +- **The Bash tool resets its working directory between calls.** Use absolute paths; never + `git add -A` after a relative `cd`. + +When a probe legitimately fails: send it back (§2). Small, deeper defects found on the way get +fixed with a regression test; unrelated ones become issues. Two classics to stay paranoid about: +generated code that does not compile for some option combination, and a silent change of the wire +format (§7). + +## 5. The verification gate (before every commit) + +```bash +mvn clean install # api → generator → plugin, all unit tests + +# If generator output changed: regenerate every checked-in test source and review the diff. +J=$(ls $PWD/de.haumacher.msgbuf.generator/target/msgbuf-generator-*-full.jar) # absolute, before the cd +cd de.haumacher.msgbuf.generator +for p in $(find src/test/java -name '*.proto'); do java -jar $J -out src/test/java $p; done +git status --short # every changed file must be explained by the change +cd .. && mvn clean install # the regenerated sources compile and pass +``` + +- **The checked-in generated test sources are golden files.** On `main`, regenerating them yields + zero diff. The loop prints `ERROR: Map types not supported in XML: …` (five times) and a + `Duplicate index '1' for 'RUNNING' and 'STARTED'` notice for the existing test protos — expected, + not a failure. After a generator change, the diff of `src/test/java/test/**` *is* the review of the + generated code: an unexplained change is a regression. +- **AST change** (`ast/proto.proto`): regenerate the AST classes with the previous generator + (`java -jar $J -out src/main/java src/main/java/de/haumacher/msgbuf/generator/ast/proto.proto`), + then rebuild. The build does not do this for you. +- **Grammar change** (`parser/protobuf.jj`, next to the parser sources): the JavaCC plugin + regenerates the parser into `src/main/java` during the build; the regenerated parser files are + checked in and ride the same commit. +- **TypeScript target**: `TestTypeScriptGenerator` compares against + `src/test/resources/ts/expected`; update with `-Dmsgbuf.ts.update=true`, then review the diff and + rerun without the flag. Type-check the golden files plus a usage file with `@ts-expect-error` + negative cases in the scratchpad: + `npx -y -p typescript tsc --strict --noEmit --isolatedModules --verbatimModuleSyntax --moduleResolution bundler --module esnext --target es2020 `. +- **Maven plugin changes**: also run `mvn install -Prun-its -pl msgbuf-generator-maven-plugin`. +- The Eclipse plugin (`de.haumacher.msgbuf.eclipse`, `de.haumacher.msgbuf.feature`) is not in + the reactor; changes there need a separate Eclipse/PDE build and are rare. + +All green or no commit. Never trust a green result from a tree with uncommitted foreign edits; +check `git status` first. When reporting, give the numbers (tests per module) and say what was +*not* run — the user asks. + +## 6. Branches, commits, PRs, releases + +- **Issue work goes through a branch and a PR** (`feature/issue--`, `fix/issue--` + in `msgbuf/msgbuf`, as for #12–#14), `Closes #` in the PR body. Small doc and chore fixes + may go straight to `main` when the user says so. External contributions arrive as PRs from forks. +- **House style**: an imperative one-line title stating the change, then a paragraph of the why + (never a bullet changelog), ending with the Co-Authored-By line from the harness rules. + Regenerated files ride the same commit as the change that produced them. +- **`CHANGELOG.md`**: every user-visible change gets an entry under the next version (the current + SNAPSHOT), in the existing sections (New Features, Bug Fixes). README documents every new + syntax element, option and generator switch. +- **PR descriptions** stay true to the branch: when a follow-up commit changes behavior, update the + description in the same step (§4 for the `gh` workaround). +- **The agents don't commit; you do**, after review. Pushing and force-pushing a shared branch are + the user's call; a history rewrite of a PR branch others may have checked out needs explicit consent. +- **Merge verified PRs yourself.** A PR that passed the probe review (§4) and the gate (§5) is + merged, not left open for the user. Use a merge commit, like the history (`gh api -X PUT + repos/msgbuf/msgbuf/pulls//merge -f merge_method=merge`; `gh pr merge` may hit the GraphQL error + of §4). Merge stacked PRs bottom-up, retargeting the next one to `main` first (`gh api -X PATCH + …/pulls/ -f base=main`), and delete a merged branch only after nothing is based on it. A PR that + conflicts with `main` gets `main` merged in, then the gate runs on that merged tree before it lands. + Stop at PRs that carry an open design question, and say so. +- **Releases are the user's**: `mvn release:clean release:prepare` pushes a `msgbuf-api-` + tag, and the tag push runs `.github/workflows/release.yml`, which deploys to Maven Central + (HOWTO-RELEASE.md). Never run `release:*`, never push a `msgbuf-api-*` tag, never edit the + version numbers the release plugin manages. + +## 7. Wire-format and generated-code doctrines (enforce in every brief and review) + +- **The wire formats are a contract with deployed peers.** JSON, binary and XML written by one + msgbuf version are read by another (TopLogic servers and clients, Dart and TypeScript consumers). + A change in what a generated writer emits is a breaking change: it needs an explicit decision, + a README and CHANGELOG note, and readers that still accept the old form. Readers stay lenient + (missing properties take defaults). +- **All targets describe one format.** The Java writer is the reference; the Dart and TypeScript + targets must describe exactly what it writes (property names = `*__PROP` constants, enum + protocol names, nullable fields omitted, polymorphic tuples). Verify against the Java generator, + not against the docs. +- **Generated code must compile for every option combination** and stay GWT-compatible: no + `java.io` Reader/Writer in `msgbuf-api` or generated code, no features beyond the language level + of the root pom, no dependencies beyond `msgbuf-api`. +- **The generator rejects, it doesn't emit garbage.** Invalid input gets an error naming the + file and definition (see #16, #21 for the failure mode to avoid: a crash or uncompilable output). +- **Names are honest.** Generated and internal names say what a thing is (the TypeScript types are + `…Json` because they describe the JSON format, not the data). The user will notice a name that + claims more than it delivers. +- **Licenses**: `msgbuf-api` is Apache-2.0, the generator GPL-3.0-or-later, generated code is + unencumbered. Generated code may only depend on `msgbuf-api`; don't copy generator code into + templates of generated code. +- **Everything generic**: a fix shaped like the bug report is not done. It must hold for nested, + inherited, cross-file and option-varied variants of the reported case (the probe of §4). + +## 8. Working with this user + +The user is the author of msgbuf, an expert in Java, code generation and software architecture, +and a main downstream consumer (TopLogic). They review sharply and ask for evidence: "did you run +the tests???" is answered with the command, the counts per module, and what was not run — never +with an unqualified "yes". Their design remarks are usually complete (e.g. naming the generated +TypeScript types after what they are); restate the design crisply, adopt it, and credit it in the +commit message. Answer questions with the mechanism first, then the recommendation. When they +overrule a suggestion ("keep one PR"), follow it without relitigating. diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..c05e4383 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,80 @@ +# Deploys a release to Maven Central when a release tag is pushed. +# +# The tag is created by `mvn release:clean release:prepare` (tag format msgbuf-api-, +# see tagNameFormat of the maven-release-plugin in pom.xml), which also pushes it. This workflow +# then builds the tagged sources, signs the artifacts and publishes them through the Central +# Portal (central-publishing-maven-plugin) - the part `mvn release:perform` did before. +# +# Required repository secrets: +# CENTRAL_USERNAME - user name of a Central Portal user token (https://central.sonatype.com/account) +# CENTRAL_PASSWORD - password of that user token +# GPG_PRIVATE_KEY - ASCII-armored secret signing key (gpg --armor --export-secret-keys ) +# GPG_PASSPHRASE - passphrase of that key +# +# A manual run (workflow_dispatch) builds and signs the current branch without deploying, +# to check the build and the signing secrets before cutting a release. + +name: Release to Maven Central + +on: + push: + tags: + - 'msgbuf-api-*' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + +jobs: + release: + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - name: Check out + uses: actions/checkout@v5 + + - name: Set up JDK, Maven settings and signing key + uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: '21' + cache: maven + server-id: central + server-username: CENTRAL_USERNAME + server-password: CENTRAL_PASSWORD + gpg-private-key: ${{ secrets.GPG_PRIVATE_KEY }} + + - name: Check that the tag matches the project version + if: github.event_name == 'push' + run: | + version=$(mvn -B -q -N help:evaluate -Dexpression=project.version -DforceStdout) + tag="${GITHUB_REF_NAME}" + echo "Tag: ${tag}, project version: ${version}" + if [ "${tag}" != "msgbuf-api-${version}" ]; then + echo "::error::Tag ${tag} does not match project version ${version} (expected msgbuf-api-${version})." + exit 1 + fi + case "${version}" in + *-SNAPSHOT) + echo "::error::Refusing to release snapshot version ${version}." + exit 1 + ;; + esac + + - name: Build and sign (dry run) + if: github.event_name != 'push' + run: mvn -B -Possrh clean verify + env: + MAVEN_GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} + + - name: Deploy to Maven Central + if: github.event_name == 'push' + run: mvn -B -Possrh clean deploy + env: + CENTRAL_USERNAME: ${{ secrets.CENTRAL_USERNAME }} + CENTRAL_PASSWORD: ${{ secrets.CENTRAL_PASSWORD }} + MAVEN_GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 236509e0..c8aae8dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,17 +1,106 @@ # Changelog -## 1.2.3 +## 1.3.0 ### New Features -- **TypeScript type definitions**: Generate a types-only TypeScript module per `.proto` file describing its JSON +- **TypeScript type definitions**: Generate a TypeScript module per `.proto` file describing its JSON format (interfaces for messages, string-literal unions for enums, type-tagged tuple unions for polymorphic values). Top-level types are named with the suffix `Json` (e.g. `ShapeJson`, `AnyShapeJson`), since they describe the JSON format, not the data itself. Properties the Java writer always emits are required, only nullable fields are optional. Enabled for all files with the Maven plugin parameter `typeScriptOutputDirectory` or the `-ts ` CLI argument, or per file with `option TypeScript = "path/to/module.ts";`. + For polymorphic values, the modules contain small helpers operating on the plain JSON values (#10): a visitor + interface and an exhaustive dispatch function (`visitShapeJson(value, visitor)`, with a required `visitDefault` for + `option OpenWorld`) and a type guard checking the type tag (`isAnyShapeJson(value)`) per `Any...Json` union, and a + function creating the type-tagged tuple per concrete type (`tagCircle(self)`). No helpers are generated for + `option SharedGraph`. Helper names that would clash (e.g. of `message A_B` and a nested `A.B`) are rejected. - **File documentation comment**: A doc comment before the `syntax` or `package` declaration is kept as the documentation of the `.proto` file (`DefinitionFile.comment`) and emitted as TSDoc `@packageDocumentation` of the TypeScript module. +### Bug Fixes +- **Nested polymorphic hierarchies** (#16): An abstract message nested in another message no longer crashes the + generator with a `NullPointerException`. Nested sub-messages of a top-level abstract message are referenced by + their qualified names in the generated JSON and XML readers (previously uncompilable). For `option OpenWorld`, the + "same file" test for local subtypes and the implied `NoBinary` of extension files now also hold for nested + definitions. +- **Maven plugin parameter names** (#17): The parameters `input`, `outputDirectory`, `resourceOutputDirectory` and + `includePaths` can be set under these names in the plugin ``. Before, only the user properties + (`-DoutputDir=…`) worked, and the README's `` was silently ignored. +- **Format options for enums** (#20): `option NoBinary` and `option NoJson` (and the implied `NoBinary` of + `option SharedGraph` and `option OpenWorld`) now also suppress the binary and JSON methods of enums. + **Source compatibility:** a file that uses an enum of another file in a format the other file disables did compile + before, because enums always had all methods. It is now rejected with an error naming both files and the option, + as are references to messages of such files and mixed `option SharedGraph` references, which generated uncompilable + code before. The generator (CLI and Maven plugin) now stops without writing code when it finds such errors. +- **XML format: transient and derived fields** (#29): `transient` fields are no longer written in XML format, like in + JSON and binary format. **Wire format change:** XML documents no longer contain these attributes and elements; + readers ignore them in documents of earlier versions. The same applies to derived references (`@Container`, + `@Reverse`): writing an object whose container was set to XML recursed endlessly (`StackOverflowError`). +- **Redeclared fields** (#21): A field that redeclares an inherited field (directly or through any generalization, + also across files), a field declared twice, and fields whose names generate the same Java names (e.g. `foo_bar` and + `fooBar`) are rejected with an error. Before, the generator silently produced Java code that did not compile. +- **Extensions across files require OpenWorld** (#25): A message that extends a message of another file is rejected + unless that file declares `option OpenWorld`. Extending from another package produced Java that did not compile. + **Source compatibility:** extending a message of an only imported (not generated together) file of the same package + compiled before, but the readers of the base did not know the subtype. It is now rejected as well. A closed + hierarchy split into files of the same package that are generated together is still accepted. Inheritance cycles + are rejected with an error instead of crashing the generator. +- **Nested specializations of the outer message** (#32): A message nested in its own generalization (e.g. + `abstract message Expr { message Sum extends Expr {…} }`) crashed the generator with a `StackOverflowError`. +- **Consistent options across `extends`** (#37, #38, #39, #40, #41): A message that extends a message of another + file is rejected if the files disagree on the serialization formats, `NoVisitor`, `NoVisitorExceptions`, + `NoTypeKind` or `NoInterfaces`, or if it adds listener or reflection support its generalization lacks. These + combinations generated uncompilable code. The exception is `NoJson` (or `NoXml`) only on an OpenWorld extension + file: it compiled, but the extension type was written without its own fields and could not be read. It is rejected + now as well. `option OpenWorld` on a file whose hierarchy root is in a file without it, and `OpenWorld` combined + with `SharedGraph` or `NoInterfaces` (before only a message on the console), are rejected. `option NoVisitor` now + also suppresses the visitor of OpenWorld extension types. +- **OpenWorld readers of abstract intermediates** (#26): The JSON reader of an abstract message below the root of an + `option OpenWorld` hierarchy (e.g. `Bird` in `Animal > Bird > Parrot`, top-level or nested) no longer fails to + compile. It reads the types of other files registered with the root, if they are specializations of the message; a + registered type of another subtree is skipped like an unknown type (the reader returns `null`). This also works for + abstract intermediates declared in extension files (which need `option OpenWorld` to be extended themselves), at any + depth. All concrete messages of an extension file below an OpenWorld message of another file are now registered, + also those extending a message of their own file. Visiting a type of an extension-file intermediate with a visitor + that does not know it calls `visitDefault()`, and such types return `null` from `kind()`. The JSON readers load the + type registrations themselves (before, reading an extension type returned `null` unless some implementation class + of the hierarchy had been initialized before). +- **OpenWorld XML readers** (#27): The XML readers of an `option OpenWorld` hierarchy (root and abstract intermediates) + now read the types of other files. The generated registration class (e.g. `Ext1Types`) additionally registers the + XML element name of each extension type with the root (`registerXml()`, `XML_REGISTRY`), if the files generate XML. + The wire formats are unchanged. +- **Primitive types in XML and binary format** (#44): `bytes`, `fixed32` and `uint32` fields no longer generate + uncompilable XML code (all versions since 1.1.0). `bytes` are written in Base64, `fixed32`/`uint32` as unsigned + decimal (the readers also accept the signed form). Nullable fields that are not set are omitted in XML format, and + `bytes` fields without a value in XML and binary format, instead of failing with a `NullPointerException`. An empty `repeated` + value (written as empty attribute) is read as empty list (before, reading failed for numbers, and a list of strings + contained one empty string). In binary format, `sint32`/`sint64` values are now written zig-zag encoded and + `fixed32`/`sfixed32`/`fixed64`/`sfixed64` values in fixed length, as the readers always expected, and 64 bit values + above 32 bits are read correctly (fix in `msgbuf-api`). **Wire format change:** the binary encoding of these six + types changes; values written before could not be read back correctly (except `0`), and writing a `repeated` field + of these types failed. +- **Clashing type IDs in a hierarchy** (#45): Two concrete specializations of an abstract message with the same type + ID (by default the simple name, e.g. a top-level `Item` and a nested `Msg.Item`, or an equal `@Name`), the same XML + element name, or the same explicit `@type_id`, also in extension files of an `option OpenWorld` hierarchy generated + together, are rejected with an error naming both definitions. So are messages of one hierarchy with the same + `TypeKind` constant (fix: rename, or `option NoTypeKind`), and a message with the name of a nested definition of + one of its generalizations, which the generated class could not refer to. A top-level specialization whose simple + name is shadowed by a nested definition in the scope of its generalization is referenced by its qualified name in + the readers (before, the reader dispatched to the nested definition). **Source compatibility:** these definitions + generated uncompilable code before (or silently wrong readers), except equal type IDs in the `option OpenWorld` + registry of extensions of different files, where the last registered type won. +- **Name resolution across packages** (#46): An unqualified type name resolves (after nested definitions of the + message using it and its outer messages) to a definition of the package of the file using it, then to a definition + of the files it imports (directly, then indirectly), and only then to a definition of any other file generated in + the same run, if it is unique (see README, "Type names and imports"). Before, one global table of simple names was + used, and the definition of the last file loaded won. So the resolution of a file's names no longer depends on + unrelated files generated together, as long as it uses definitions of its own package or its imports. Duplicate + definitions in a package (in one or several files) stop the generation with an error naming the files, instead of + only a message on the console. A file given to the generator twice, or given after it + has been loaded as an import, is loaded only once (and generated). **Source compatibility:** an unqualified name + that is defined in two imported files (at the same import depth), or not in the own package or imports but in + several other files generated together, is now rejected as ambiguous; use a qualified name. + ## 1.2.1 ### Bug Fixes diff --git a/CLAUDE.md b/CLAUDE.md index f5276c1b..4600bed1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -53,7 +53,7 @@ Key source locations: - Generator entry point: `de.haumacher.msgbuf.generator.Generator` - Code generators: `de.haumacher.msgbuf.generator.MessageGenerator`, `EnumGenerator` - Other targets: Dart (`generator.dart.DartLibGenerator`, `option DartLib`), TypeScript types (`generator.ts.TypeScriptGenerator`, `-ts ` / Maven `typeScriptOutputDirectory` / `option TypeScript`; golden-file test `TestTypeScriptGenerator`, update expected files with `-Dmsgbuf.ts.update=true`) -- JavaCC grammar: `de.haumacher.msgbuf.generator/src/main/javacc/protobuf.jj` +- JavaCC grammar: `de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/protobuf.jj` (next to the generated parser sources) - AST proto definition: `de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/proto.proto` ## Runtime API Architecture @@ -83,9 +83,9 @@ Extensions beyond standard protobuf: ## Key Gotchas -- **Self-bootstrapping**: Changes to `generator/ast/proto.proto` require regenerating the AST Java classes with an existing generator, then rebuilding. Maven reactor handles this automatically. +- **Self-bootstrapping**: Changes to `generator/ast/proto.proto` require regenerating the AST Java classes with an existing generator, then rebuilding. The build does **not** do this: run `java -jar de.haumacher.msgbuf.generator/target/msgbuf-generator-*-full.jar -out de.haumacher.msgbuf.generator/src/main/java de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/proto.proto` (or the Eclipse launch config `de.haumacher.msgbuf.generator/bin/Generate Compiler AST.launch`). Likewise, the checked-in generated test sources under `src/test/java/test/**` are regenerated by hand (`-out src/test/java` for each `.proto`). - **NoInterfaces mode**: When set, generates single classes instead of interface + impl. Changes package structure (no `impl` subpackage). Many conditionals in `MessageGenerator` depend on this flag. -- **Polymorphic JSON**: Abstract types serialize as `[type, ...fields]` arrays. Concrete types in hierarchies use same format. Monomorphic references use `writeContent()` without type info. +- **Polymorphic JSON**: In a hierarchy with an abstract root, a value is written as a two-element array `[typeId, {fields}]` (the root's final `writeTo()`). A field declared with a concrete type of such a hierarchy uses `writeContent()` and writes the plain object without type info. A hierarchy with a concrete root carries no type info at all. - **Field IDs**: Auto-synthesis starts at 1, skips manually assigned IDs, is inheritance-aware (child fields can't clash with parent IDs). Field ID 0 is reserved. - **Tests use JUnit 3 style** (`extends TestCase`) despite JUnit 4 dependency. Tests exercise generated code, not the generator itself directly. - **GWT constraint**: No Java I/O classes in `msgbuf-api`. No Java 8+ features in generated code. @@ -105,5 +105,5 @@ Maven plugin integration tests: `msgbuf-generator-maven-plugin/src/it/` - Java 11+ required (`maven.compiler.source/target = 11`) - Generated code must be GWT-compatible (no `java.io` usage in `msgbuf-api`) -- Generator uses JavaCC — regenerate parser after grammar changes to `protobuf.jj` +- Generator uses JavaCC — the `javacc-maven-plugin` regenerates the parser into `src/main/java` during the build after grammar changes to `protobuf.jj`; the generated parser sources are checked in and must be committed with the grammar change - Different licenses: API is Apache-2.0, Generator is GPL-3.0-or-later (generated code is not GPL-encumbered) diff --git a/HOWTO-RELEASE.md b/HOWTO-RELEASE.md index 060c13d9..f804cc66 100644 --- a/HOWTO-RELEASE.md +++ b/HOWTO-RELEASE.md @@ -6,18 +6,44 @@ mvn release:clean release:prepare ``` +This sets the release version, commits, creates the tag `msgbuf-api-`, sets the next +snapshot version, commits again and pushes both commits and the tag. + ## Release to Maven Central -``` -mvn release:perform -``` +Pushing the tag starts the GitHub workflow `.github/workflows/release.yml` ("Release to Maven +Central"). It checks that the tag matches the project version, builds the tagged sources, signs the +artifacts and publishes them through the Central Portal. It waits until the deployment is +published. Follow it in the repository's Actions tab. + +Do **not** run `mvn release:perform` in addition: the version would be deployed twice, and the +second deployment is rejected by Maven Central. +The workflow needs these repository secrets (Settings → Secrets and variables → Actions): + +| Secret | Content | +|--------------------|-------------------------------------------------------------------------| +| `CENTRAL_USERNAME` | User name of a Central Portal user token (central.sonatype.com → Account → Generate User Token) | +| `CENTRAL_PASSWORD` | Password of that user token | +| `GPG_PRIVATE_KEY` | ASCII-armored signing key: `gpg --armor --export-secret-keys ` | +| `GPG_PASSPHRASE` | Passphrase of that key | + +To check the build and the signing secrets without releasing, run the workflow manually (Actions → +Release to Maven Central → Run workflow): it builds and signs the selected branch but does not +deploy. + +A failed deployment can be repeated by re-running the workflow for the tag, as long as nothing was +published yet. ## Signing -Artifacts are GPG signed only in the `ossrh` profile. `release:perform` activates it automatically (see -`releaseProfiles` of the `maven-release-plugin`), so a regular `mvn install` does not require a GPG key. -For a manual deployment to Maven Central, activate the profile explicitly: +Artifacts are GPG signed only in the `ossrh` profile. The release workflow and `release:perform` +activate it, so a regular `mvn install` does not require a GPG key. The key passphrase is read from +the environment variable `MAVEN_GPG_PASSPHRASE` if set, otherwise the gpg-agent is asked. + +For a manual deployment to Maven Central (e.g. if GitHub Actions is unavailable), check out the +tag and activate the profile explicitly. This needs the `central` server credentials in +`~/.m2/settings.xml`: ``` mvn deploy -Possrh diff --git a/README.md b/README.md index fe703035..e4d575cb 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ In contrast to `protobuf`, `msgbuf` supports: de.haumacher.msgbuf msgbuf-api - 1.2.1 + 1.3.0 ``` @@ -32,7 +32,7 @@ To the `build/plugins` section add: de.haumacher.msgbuf msgbuf-generator-maven-plugin - 1.2.1 + 1.3.0 @@ -51,6 +51,21 @@ Now you are ready to create `*.proto` files in your source folder and build them Proto files are placed in your Java source folder (`src/main/java/`) inside the directory matching their `package` declaration. The generated Java files are written next to the proto file. For example, a proto file with `package my.app.model;` should be placed at `src/main/java/my/app/model/shape.proto`, and the generated classes will appear in `src/main/java/my/app/model/`. +### Plugin parameters + +All parameters are optional. Set them in the `` of the plugin (or its execution), or with the user +property on the command line (`-D=...`): + +| Parameter | User property | Default | Description | +|---|---|---|---| +| `input` | `input` | `${project.build.sourceDirectory}` | Directory searched for `.proto` files (or a single `.proto` file). | +| `outputDirectory` | `outputDir` | `${project.build.sourceDirectory}` | Directory the Java sources are generated to. | +| `resourceOutputDirectory` | `resourceOutputDir` | `${project.basedir}/src/main/resources` | Directory resource files (`META-INF/services`) are generated to. | +| `typeScriptOutputDirectory` | `typeScriptOutputDir` | none | Directory TypeScript types are generated to (see [TypeScript](#typescript-type-definitions)). | +| `includePaths` | `includePaths` | none | Additional directories searched for imported `.proto` files. | + +If `outputDirectory` is not a source folder of the project, add it as one (e.g. with the `build-helper-maven-plugin`). + ## Usage The `msgbuf` definition language is an extension of the [proto format](https://developers.google.com/protocol-buffers/docs/proto3) from `protobuf`. A defined message can `extend` another message type, or it can be marked `abstract`. @@ -90,6 +105,11 @@ message Group extends Shape { Passing these definitions to the `msgbuf` compiler gives you a class hierarchy with classes `Shape`, `Circle`, `Rectangle`, and `Group`. You can inspect the generation result in the test package [test.hierarchy](https://github.com/msgbuf/msgbuf/tree/main/de.haumacher.msgbuf.generator/src/test/java/test/hierarchy/data) of the compiler. The source of the example data class definitions can be seen in the [hierarchy.proto](https://github.com/msgbuf/msgbuf/tree/main/de.haumacher.msgbuf.generator/src/test/java/test/hierarchy/data/hierarchy.proto) file. +A sub-message inherits all fields of its generalizations and cannot redeclare them, not even to narrow the type. The +names of all fields of a message, including the inherited ones, must also generate distinct Java names: `foo_bar` +and `fooBar` both generate `getFooBar()`. The generator rejects such definitions with an error naming the field and +the message declaring the other one. + ### Enum types Enums define a fixed set of named constants. Each constant is terminated with a semicolon. Constants can optionally @@ -130,9 +150,29 @@ message SearchResponse { } ``` +### Type names and imports + +Messages and enums of other `.proto` files are made available with `import "path/to/other.proto";` (resolved relative +to the importing file, then in the include paths, then on the classpath). A type can always be referenced by its +qualified name (`package.Type`, `package.Outer.Inner`). An unqualified name `Type` (or `Type.Inner`) is resolved in +the following order; the first step that finds a definition wins: + +1. A nested definition of the message using the name, or of one of its outer messages (innermost first). +2. A top-level definition of the package of the file using the name (in any file of that package generated in the same + run). +3. A top-level definition of a file imported by that file. If none of the imported files defines the name, the files + they import are searched, and so on. Two definitions found in the same step are an error: use a qualified name. +4. For compatibility, a top-level definition of any other file generated in the same run, if exactly one file defines + the name. Otherwise, the name is rejected as ambiguous. + +Because of step 3, adding an unrelated file to the files generated together (e.g. a new `.proto` file in a Maven +project) does not change how the names of a file resolve, as long as the definitions it uses come from its own package +or its imports. A package must not define a top-level name twice, not even in different files. + ### Transient fields -Fields marked with `transient` are not serialized. They exist only in the in-memory representation: +Fields marked with `transient` are not serialized in any format (JSON, binary, XML). They exist only in the in-memory +representation. Readers ignore values of transient fields, e.g. in XML documents written by versions before 1.3.0: ```protobuf message A { @@ -196,14 +236,29 @@ For binary serialization, json values are wrapped in a `JsonValue` message envel ## Global protocol options ### `option NoJson` -Disables generation of read and write methods for the JSON format. +Disables generation of read and write methods for the JSON format (for messages and enums). ### `option NoBinary` -Disables generation of read and write methods for binary format. +Disables generation of read and write methods for binary format (for messages and enums). ### `option NoXml` Disables generation of read and write methods for XML format. +The format options apply to all messages and enums of a file. A message that references a message or enum of another +file (as field type or with `extends`) needs the read and write methods of each format it generates itself in that +other file. The generator rejects a reference to a definition generated without such a format, and generates no code +in that case. Either disable the format in the referencing file as well, or enable it in the referenced one. The same +holds for `option SharedGraph`, which has its own JSON methods for messages: a message can reference messages of +another file only if both files use `option SharedGraph`, or neither does. Enums are not affected by +`option SharedGraph`. `transient` fields and derived references (`@Container`, `@Reverse`) are not serialized, so they +don't need these formats. + +A message that extends a message of another file implements and overrides its generated methods. So both files must +agree on the serialization formats, `option NoVisitor`, `option NoVisitorExceptions`, `option NoTypeKind` and +`option NoInterfaces`. A specialization may be generated without the listener (`option NoListener`) or reflection +(`option NoReflection`) support of its generalization, but not with support its generalization lacks. The generator +rejects other combinations with an error naming both files. + ### `option NoXmlNames` Disables generation of constants for the XML format. @@ -249,7 +304,13 @@ message Config { ### `option OpenWorld` Enables cross-file protocol extension for abstract type hierarchies. With this option, subtypes can be defined in -separate `.proto` files (and separate modules) using `import` and `extends`: +separate `.proto` files (and separate modules) using `import` and `extends`. + +A message can extend a message of another file only if that file declares `option OpenWorld`, so that the readers of +the hierarchy resolve types of other files. This also holds for an intermediate: to extend a message of an extension +file, the extension file must declare `option OpenWorld` as well. The only exception is a hierarchy without +`OpenWorld` that is split into several files of the same package, which are generated together. The generator rejects +other extensions across files with an error. ```protobuf // base-module: events.proto @@ -282,16 +343,24 @@ The base module's `.proto` files should be packaged as resources in its JAR (e.g The Maven plugin automatically resolves imports from compile-scope dependency JARs, so no file system paths to the base module are needed. +Readers of the hierarchy (of the root and of abstract intermediates) resolve the types of all registered +extension modules in JSON and XML format. The registration class registers the JSON type ID and, if XML is +generated, the XML element name of each extension type with the root of the hierarchy. A reader of an abstract +intermediate only accepts registered types that specialize the intermediate. An unknown type (or a registered +type of another subtree) is skipped, and the reader returns `null`. An abstract message of an extension file can +itself be extended in further files, if the extension file declares `option OpenWorld`, too. + Implications: - Implies `option NoBinary` (only JSON and XML serialization are supported) -- Cannot be combined with `option NoInterfaces` +- Cannot be combined with `option NoInterfaces` or `option SharedGraph` +- The root's file must declare `option OpenWorld` if any file of the hierarchy does - The generated `Visitor` interface includes a `visitDefault()` fallback method for unknown extension types - Extension types generate their own `Visitor` sub-interface with an `instanceof`-based dispatch Maven plugin configuration (extension module): ```xml - ${project.basedir}/src/main/resources + ${project.basedir}/src/main/resources ``` @@ -375,7 +444,8 @@ Sets a custom tag name for XML serialization. Marks a reference to be the reverse end of the reference with the given name in the target type. ### `@Container` -Marks a reference point to the container of the current object. +Marks a reference point to the container of the current object. The container reference is derived from the +containment and not serialized. ### `@Ref` Marks a reference as cross reference (non-composition). When setting values to fields marked as cross reference, container properties are not updated. @@ -447,8 +517,9 @@ message MyMessage { ### TypeScript type definitions The generator can create a TypeScript module with type definitions for the JSON format of each `.proto` file. The -modules contain types only (no readers, writers or other runtime code) and let a TypeScript client share the protocol -contract with the Java side. +modules let a TypeScript client share the protocol contract with the Java side. Besides the types, they only contain +small helper functions for type-tagged polymorphic values (visitor dispatch, tagging, tag guards, see below) that +operate on the plain values of `JSON.parse()`: no classes, no readers or writers, no runtime library. Since the types describe the JSON format and not the data itself, a top-level type is named after its definition with the suffix `Json`, e.g. `ShapeJson` for `message Shape`. This keeps the plain names free for types representing the @@ -492,6 +563,8 @@ Mapping of protocol definitions: | `map` (other key types) | `Array<{ key: K; value: V }>` | | Nested definitions | Declarations in a namespace named after the outer message, keeping their names, e.g. `OuterJson.Inner` | | Types from imported `.proto` files | `import type { ... } from '';` | +| `abstract message A` with `AnyAJson` | Visitor interface `AJsonVisitor`, dispatch function `visitAJson(value, visitor)`, type guard `isAnyAJson(value)` | +| `message C extends A` (in a hierarchy with abstract root) | Function `tagC(self: CJson): ['TypeIdOfC', CJson]` creating the type-tagged tuple | Details: @@ -521,6 +594,48 @@ Details: generated and used as type of fields referencing `A`. For `option OpenWorld` hierarchies, the union additionally contains `[string, AJson]` for extension types from other modules. References to concrete messages (and all messages in a hierarchy with a concrete root) are written without type information and use the interface directly. +* **Helpers for polymorphic values**: For each union `AnyAJson`, a visitor interface with one method per concrete + type of the union, a dispatch function and a type guard are generated, and a tag function for each concrete type + of such a hierarchy: + + ```ts + export interface SSEEventJsonVisitor { + visitPatchEvent(self: PatchEventJson): R; + visitStateEvent(self: StateEventJson): R; + } + export function visitSSEEventJson(value: AnySSEEventJson, visitor: SSEEventJsonVisitor): R; + export function isAnySSEEventJson(value: unknown): value is AnySSEEventJson; + export function tagPatchEvent(self: PatchEventJson): ['PatchEvent', PatchEventJson]; + ``` + + Usage: + + ```ts + const event: unknown = JSON.parse(data); + if (isAnySSEEventJson(event)) { + visitSSEEventJson(event, { + visitPatchEvent: patch => applyPatch(patch), + visitStateEvent: state => replaceState(state), + }); + } + socket.send(JSON.stringify(tagPatchEvent({ timestamp: Date.now(), patch: '...' }))); + ``` + + * The name part of a helper (`SSEEvent`, `PatchEvent`) is the message name qualified with the names of its outer + messages, joined with `_`, first letter in upper case, e.g. `visitGroup_Info` and `tagGroup_Info` for message + `Info` nested in `Group`. The package is not part of the name. All helpers are declared at the top level of the + module, also for nested messages (a namespace containing functions is not erasable TypeScript syntax). The + generator rejects a `.proto` file whose helper names clash, i.e. two concrete types of one hierarchy (also from + different files) or two messages of one file with the same name part, e.g. `message A_B` and `A.B`. + * A visitor method has the same name in the visitors of all abstract types of a hierarchy, so a visitor of the root + can also be passed to the dispatch function of an abstract intermediate type. + * The dispatch function of a closed hierarchy is checked for exhaustiveness by the compiler and throws an `Error` + for an unknown type ID. For `option OpenWorld` hierarchies, the visitor has an additional required method + `visitDefault(self: AJson, typeId: string)` that receives values of types not known to the module (like the + `visitDefault()` of the Java visitor). + * The type guard checks the type tag only: an array of two elements, the first a known type ID (any string for + `option OpenWorld`), the second an object. The properties of the object are not validated. + * Tag functions return the exact tuple type, which is assignable to each `Any...Json` union containing the type. * **Documentation**: Doc comments become TSDoc comments. JavaDoc inline tags are translated: `{@code x}` becomes `` `x` ``, `{@link Type}`, `{@link #field}` and `{@link Type#field label}` become links to the TypeScript type or property (`{@link Type.prop label}`, using the JSON property name), a link to an enum constant becomes its protocol @@ -532,7 +647,7 @@ Details: at the location the same generator configuration would produce for it (its `option TypeScript`, or its package path within the TypeScript output directory). * **Limitations**: The JSON format of `option SharedGraph` protocols (objects as `[type, id, {...}]`, references as - IDs, incremental updates) is not described by the generated types. A generated `AnyAJson` union type may clash with + IDs, incremental updates) is not described by the generated types, no helper functions are generated for them. A generated `AnyAJson` union type may clash with a message named `AnyA`. ## Installation in Eclipse diff --git a/de.haumacher.msgbuf.generator/pom.xml b/de.haumacher.msgbuf.generator/pom.xml index 059fc0bb..3f38245b 100644 --- a/de.haumacher.msgbuf.generator/pom.xml +++ b/de.haumacher.msgbuf.generator/pom.xml @@ -4,7 +4,7 @@ de.haumacher.msgbuf msgbuf-parent - 1.2.3-SNAPSHOT + 1.3.1-SNAPSHOT msgbuf-generator @@ -34,7 +34,7 @@ de.haumacher.msgbuf msgbuf-api - 1.2.3-SNAPSHOT + 1.3.1-SNAPSHOT diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/AbstractMessageGenerator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/AbstractMessageGenerator.java index 2436e5ba..c9cd9723 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/AbstractMessageGenerator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/AbstractMessageGenerator.java @@ -71,7 +71,7 @@ protected String qImplName(MessageDef def) { protected static List concreteSpecializations(MessageDef def) { ArrayList result = new ArrayList<>(); - addConcreteSpecializations(result, def, def.getFile()); + addConcreteSpecializations(result, def, Util.definingFile(def)); return result; } @@ -95,7 +95,7 @@ protected static List localSpecializations(MessageDef def, Definitio return def.getSpecializations(); } return def.getSpecializations().stream() - .filter(s -> s.getFile() == originFile) + .filter(s -> Util.definingFile(s) == originFile) .collect(Collectors.toList()); } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/CodeConvention.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/CodeConvention.java index 588fd329..902f54c4 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/CodeConvention.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/CodeConvention.java @@ -279,7 +279,42 @@ public static String jsonTypeConstant(MessageDef def) { } public static String jsonTypeConstantRef(MessageDef def) { - return typeName(def) + "." + jsonTypeConstant(def); + String typeRef = simpleNameInScopeOfGeneralizations(def) ? typeName(def) : qTypeName(def); + return typeRef + "." + jsonTypeConstant(def); + } + + /** + * Whether the given message can be referenced by its simple name (the simple name of its + * interface or implementation class) from the generated code of its generalizations. + * + *

+ * A nested specialization is not in scope by its simple name in the code of its generalization. + * A top-level specialization is in scope, unless a nested definition with the same name + * shadows it: a nested definition of a generalization, of one of its outer messages, or of one + * of their generalizations. In these cases, the qualified name must be used. + *

+ */ + public static boolean simpleNameInScopeOfGeneralizations(MessageDef def) { + if (def.getFile() == null) { + return false; + } + String name = def.getName(); + java.util.Set seen = new java.util.HashSet<>(); + for (MessageDef generalization = def.getExtendedDef(); generalization != null && seen.add(generalization); + generalization = generalization.getExtendedDef()) { + for (MessageDef scope = generalization; scope != null; scope = scope.getOuter()) { + java.util.Set seenInherited = new java.util.HashSet<>(); + for (MessageDef inherited = scope; inherited != null && seenInherited.add(inherited); + inherited = inherited.getExtendedDef()) { + for (Definition member : inherited.getDefinitions()) { + if (member.getName().equals(name)) { + return false; + } + } + } + } + } + return true; } public static String mkBinaryTypeConstant(MessageDef def) { diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/EnumGenerator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/EnumGenerator.java index 08d3dafd..cc14f4a1 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/EnumGenerator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/EnumGenerator.java @@ -8,11 +8,13 @@ import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Set; import de.haumacher.msgbuf.generator.ast.Constant; import de.haumacher.msgbuf.generator.ast.DefinitionFile; import de.haumacher.msgbuf.generator.ast.EnumDef; +import de.haumacher.msgbuf.generator.ast.Option; import de.haumacher.msgbuf.generator.ast.QName; import de.haumacher.msgbuf.generator.common.MsgBufJsonProtocol; import de.haumacher.msgbuf.generator.util.AbstractJavaGenerator; @@ -25,13 +27,22 @@ public class EnumGenerator extends AbstractJavaGenerator { private EnumDef _def; + private final boolean _json; + + private final boolean _binary; + /** * Creates a {@link EnumGenerator}. * + * @param options + * The options of the file defining the enumeration, selecting the serialization formats. * @param def + * The enumeration to generate. */ - public EnumGenerator(EnumDef def) { + public EnumGenerator(Map options, EnumDef def) { _def = def; + _json = MessageGenerator.isJson(options); + _binary = MessageGenerator.isBinary(options); } @Override @@ -87,6 +98,17 @@ protected void generate() { } line("}"); + if (_json) { + generateJsonIO(); + } + if (_binary) { + generateBinaryIO(); + } + + line("}"); + } + + private void generateJsonIO() { nl(); line("/** Writes this instance to the given output. */"); line("public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException {"); @@ -102,7 +124,10 @@ protected void generate() { line("return " + CodeConvention.ENUM_VALUE_OF_PROTOCOL + "(in.nextString());"); } line("}"); - + } + + private void generateBinaryIO() { + List constants = _def.getConstants(); nl(); line("/** Writes this instance to the given binary output. */"); line("public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException {"); @@ -131,8 +156,6 @@ protected void generate() { line("}"); } line("}"); - - line("}"); } private void generateConstants() { diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/FieldIDSynthesizer.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/FieldIDSynthesizer.java index 32dbd079..a23cacd3 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/FieldIDSynthesizer.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/FieldIDSynthesizer.java @@ -20,6 +20,11 @@ * assigned in the message definition. */ public class FieldIDSynthesizer implements Definition.Visitor, Void> { + + /** + * Names of all fields by index for each processed message, including inherited fields. + */ + private final Map> _indexes = new HashMap<>(); /** * Assigns IDs in the given file. @@ -65,9 +70,33 @@ private void error(String message) { @Override public Map visit(MessageDef self, Void arg) { + Map result = indexes(self); + for (Definition inner : self.getDefinitions()) { + inner.visit(this, arg); + } + return result; + } + + /** + * Assigns the field indexes of the given message (and its generalizations) and returns the + * names of all its fields, including the inherited ones, by index. + * + *

+ * Walks the generalizations only, not the nested definitions: a nested message may extend its + * outer message. + *

+ */ + private Map indexes(MessageDef self) { + Map cached = _indexes.get(self); + if (cached != null) { + return cached; + } + // Guards against an inheritance cycle, which the generator rejects before. + _indexes.put(self, new HashMap<>()); + Map partByIndex; if (self.getExtendedDef() != null) { - partByIndex = self.getExtendedDef().visit(this, arg); + partByIndex = new HashMap<>(indexes(self.getExtendedDef())); } else { partByIndex = new HashMap<>(); } @@ -94,11 +123,8 @@ public Map visit(MessageDef self, Void arg) { field.setIndex(nextIndex); } } - - for (Definition inner : self.getDefinitions()) { - inner.visit(this, arg); - } + _indexes.put(self, partByIndex); return partByIndex; } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java index bac207a2..9f1fcc1a 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java @@ -14,6 +14,7 @@ import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -30,17 +31,20 @@ import de.haumacher.msgbuf.generator.ast.Flag; import de.haumacher.msgbuf.generator.ast.MapType; import de.haumacher.msgbuf.generator.ast.MessageDef; +import de.haumacher.msgbuf.generator.ast.NumberOption; import de.haumacher.msgbuf.generator.ast.Option; import de.haumacher.msgbuf.generator.ast.PrimitiveType; import de.haumacher.msgbuf.generator.ast.QName; import de.haumacher.msgbuf.generator.ast.StringOption; import de.haumacher.msgbuf.generator.ast.Type; +import de.haumacher.msgbuf.generator.common.MsgBufJsonProtocol; import de.haumacher.msgbuf.generator.common.Util; import de.haumacher.msgbuf.generator.dart.DartLibGenerator; import de.haumacher.msgbuf.generator.parser.ParseException; import de.haumacher.msgbuf.generator.parser.ProtobufParser; import de.haumacher.msgbuf.generator.parser.ProtobufParserConstants; import de.haumacher.msgbuf.generator.parser.Token; +import de.haumacher.msgbuf.generator.plugins.XmlStreamingPlugin; import de.haumacher.msgbuf.generator.ts.TypeScriptGenerator; import de.haumacher.msgbuf.generator.util.FileGenerator; @@ -94,6 +98,7 @@ public class Generator { private List _includePaths = new ArrayList<>(); private ClassLoader _importClassLoader; private Set _loadedFiles = new HashSet<>(); + private Map _fileByPath = new HashMap<>(); private List _importedFiles = new ArrayList<>(); public void setOut(File out) { @@ -136,11 +141,20 @@ public DefinitionFile load(String fileName) throws IOException, ParseException { public DefinitionFile load(File file) throws ParseException, IOException, FileNotFoundException { - _loadedFiles.add(file.getCanonicalPath()); + String canonical = file.getCanonicalPath(); + DefinitionFile loaded = _fileByPath.get(canonical); + if (loaded != null) { + // The same file given twice, or given after being loaded as import of another file: + // Generate code for it, but do not enter its definitions again. + _importedFiles.remove(loaded); + return loaded; + } + _loadedFiles.add(canonical); DefinitionFile content; try (InputStream in = new FileInputStream(file)) { content = load(parse(in)); } + _fileByPath.put(canonical, content); _sourceNames.put(content, file.getName()); resolveImports(content, file); return content; @@ -173,8 +187,14 @@ public void generate(GeneratorPlugin plugin) { buildSpecializations(file); } + List errors = new ArrayList<>(); + // Duplicate definitions and ambiguous names. + errors.addAll(_table.drainErrors(this::sourceDescription)); + if (!errors.isEmpty()) { + throw new GeneratorException(errors); + } for (DefinitionFile file : _files) { - validateOpenWorld(file); + validateOpenWorld(file, errors); } // Propagate NoBinary and NoTypeKind to extension files that extend OpenWorld bases @@ -182,6 +202,26 @@ public void generate(GeneratorPlugin plugin) { propagateOpenWorldOptions(file); } + for (DefinitionFile file : _files) { + if (!_importedFiles.contains(file)) { + validateGeneralizations(file, plugin, errors); + } + } + if (!errors.isEmpty()) { + // Checks below depend on a consistent hierarchy. + throw new GeneratorException(errors); + } + for (DefinitionFile file : _files) { + if (!_importedFiles.contains(file)) { + validateFieldNames(file, errors); + validateFormatReferences(file, plugin, errors); + } + } + validateHierarchyNames(plugin, errors); + if (!errors.isEmpty()) { + throw new GeneratorException(errors); + } + TypeIdSynthesizer typeIdSynthesizer = new TypeIdSynthesizer(); for (DefinitionFile file : _files) { if (!Util.getFlag(file, "OpenWorld")) { @@ -194,6 +234,15 @@ public void generate(GeneratorPlugin plugin) { synthesizer.process(file); } + for (DefinitionFile file : _files) { + if (!_importedFiles.contains(file) && generatesTypeScript(file)) { + TypeScriptGenerator.validate(file, this::sourceDescription, errors); + } + } + if (!errors.isEmpty()) { + throw new GeneratorException(errors); + } + for (DefinitionFile file : _files) { if (_importedFiles.contains(file)) { continue; // Imported for type resolution only, don't generate code @@ -213,7 +262,7 @@ public void generate(GeneratorPlugin plugin) { new DartLibGenerator(new File(_out, ((StringOption) dartLib).getValue()), file).run(); } - if (_tsOut != null || file.getOptions().get(TYPESCRIPT_OPTION) != null) { + if (generatesTypeScript(file)) { File tsFile = typeScriptModule(file); new TypeScriptGenerator(tsFile, file, sourceDescription(file), other -> moduleSpecifier(tsFile, typeScriptModule(other)), _table).run(); @@ -228,7 +277,7 @@ public void generate(GeneratorPlugin plugin) { } List crossFileExtensions = findCrossFileExtensions(file); if (!crossFileExtensions.isEmpty()) { - String fqClassName = generateRegistrationClass(file, crossFileExtensions); + String fqClassName = generateRegistrationClass(file, crossFileExtensions, plugin); registrationClasses.add(fqClassName); } } @@ -237,6 +286,13 @@ public void generate(GeneratorPlugin plugin) { } } + /** + * Whether a TypeScript module is generated for the given definitions. + */ + private boolean generatesTypeScript(DefinitionFile file) { + return _tsOut != null || file.getOptions().get(TYPESCRIPT_OPTION) != null; + } + /** * The TypeScript module file for the given definitions. * @@ -293,7 +349,7 @@ private static String moduleSpecifier(File from, File to) { return relative.startsWith("../") ? relative : "./" + relative; } - private void validateOpenWorld(DefinitionFile file) { + private void validateOpenWorld(DefinitionFile file, List errors) { boolean openWorld = Util.getFlag(file, "OpenWorld"); if (!openWorld) { return; @@ -301,9 +357,14 @@ private void validateOpenWorld(DefinitionFile file) { // OpenWorld implies NoBinary file.getOptions().put("NoBinary", Flag.create().setValue(true)); - boolean noInterfaces = Util.getFlag(file, "NoInterfaces"); - if (noInterfaces) { - error("option OpenWorld cannot be combined with option NoInterfaces."); + if (_importedFiles.contains(file)) { + return; + } + for (String option : new String[] { "NoInterfaces", "SharedGraph" }) { + if (Util.getFlag(file, option)) { + errors.add(sourceDescription(file) + ": option OpenWorld cannot be combined with option " + option + + ". Remove one of the options."); + } } } @@ -312,19 +373,650 @@ private void propagateOpenWorldOptions(DefinitionFile file) { // Already an OpenWorld file, options already set return; } - for (Definition def : file.getDefinitions()) { + if (extendsOpenWorldFromOtherFile(file, file.getDefinitions())) { + // Extension file inherits NoBinary from OpenWorld base + file.getOptions().put("NoBinary", Flag.create().setValue(true)); + } + } + + private static boolean extendsOpenWorldFromOtherFile(DefinitionFile file, List definitions) { + for (Definition def : definitions) { if (def instanceof MessageDef) { MessageDef msg = (MessageDef) def; MessageDef extended = msg.getExtendedDef(); - if (extended != null && extended.getFile() != file && Util.getFlag(extended.getFile(), "OpenWorld")) { - // Extension file inherits NoBinary from OpenWorld base - file.getOptions().put("NoBinary", Flag.create().setValue(true)); - return; + if (extended != null) { + DefinitionFile extendedFile = Util.definingFile(extended); + if (extendedFile != file && Util.getFlag(extendedFile, "OpenWorld")) { + return true; + } + } + if (extendsOpenWorldFromOtherFile(file, msg.getDefinitions())) { + return true; } } } + return false; } + /** + * Rejects inheritance cycles and extensions of messages of other files that are inconsistent + * with option OpenWorld. + * + *

+ * The readers of a hierarchy must know all its types. A message of another file can therefore + * only be extended if that file declares option OpenWorld, which makes its readers + * resolve extension types through a registry. The only exception is a closed hierarchy that is + * split into several files of the same package and generated together: then the readers of the + * extended message are generated with all its specializations. + *

+ */ + private void validateGeneralizations(DefinitionFile file, GeneratorPlugin plugin, List errors) { + for (Definition def : file.getDefinitions()) { + validateGeneralizations(file, def, plugin, errors); + } + } + + private void validateGeneralizations(DefinitionFile file, Definition def, GeneratorPlugin plugin, List errors) { + if (!(def instanceof MessageDef)) { + return; + } + MessageDef message = (MessageDef) def; + MessageDef extended = message.getExtendedDef(); + if (extended != null) { + int errorCount = errors.size(); + List path = new ArrayList<>(); + path.add(message); + for (MessageDef current = extended; current != null; current = current.getExtendedDef()) { + if (current == message) { + path.add(current); + errors.add(sourceDescription(file) + ": Message '" + Util.toString(message) + + "' is part of an inheritance cycle: " + + path.stream().map(Util::toString).collect(java.util.stream.Collectors.joining(" extends ")) + + ". Remove one of the extends clauses."); + break; + } + if (path.contains(current)) { + // A cycle not containing this message, reported for its members. + break; + } + path.add(current); + } + + DefinitionFile extendedFile = Util.definingFile(extended); + if (extendedFile != file && !Util.getFlag(extendedFile, "OpenWorld") + && !(samePackage(file, extendedFile) && !_importedFiles.contains(extendedFile))) { + errors.add(sourceDescription(file) + ": Message '" + Util.toString(message) + "' extends message '" + + Util.toString(extended) + "' of '" + sourceDescription(extendedFile) + + "', which does not declare option OpenWorld. Add 'option OpenWorld;' to '" + + sourceDescription(extendedFile) + "' to extend its messages in other files" + + " (a hierarchy without OpenWorld can only be split into files of the same package" + + " that are generated together)."); + } + + if (Util.getFlag(file, "OpenWorld") && errors.size() == errorCount) { + MessageDef root = extended; + Set seen = new HashSet<>(); + while (root.getExtendedDef() != null && seen.add(root)) { + root = root.getExtendedDef(); + } + DefinitionFile rootFile = Util.definingFile(root); + if (!Util.getFlag(rootFile, "OpenWorld")) { + errors.add(sourceDescription(file) + ": File declares option OpenWorld, but message '" + + Util.toString(message) + "' belongs to the hierarchy of '" + Util.toString(root) + "' of '" + + sourceDescription(rootFile) + "', which does not declare option OpenWorld. Add 'option OpenWorld;' to '" + + sourceDescription(rootFile) + "', or remove it from '" + sourceDescription(file) + "'."); + } + } + + if (extendedFile != file && errors.size() == errorCount) { + validateExtensionOptions(file, message, extended, extendedFile, plugin, errors); + } + } + + for (Definition inner : message.getDefinitions()) { + validateGeneralizations(file, inner, plugin, errors); + } + } + + /** + * Rejects an extension of a message of another file, if the two files generate incompatible + * code. + * + *

+ * A specialization implements the abstract methods and overrides the methods of its + * generalization. So both files must generate the same serialization formats, visitors and type + * kinds, and use the same interface mode. A specialization may omit listener and reflection + * support of its generalization, but cannot add it. + *

+ */ + private void validateExtensionOptions(DefinitionFile file, MessageDef message, MessageDef extended, + DefinitionFile extendedFile, GeneratorPlugin plugin, List errors) { + String prefix = sourceDescription(file) + ": Message '" + Util.toString(message) + "' extends message '" + + Util.toString(extended) + "' of '" + sourceDescription(extendedFile) + "'"; + + Set formats = formats(file, plugin); + Set extendedFormats = formats(extendedFile, plugin); + for (String format : extendedFormats) { + if (!formats.contains(format) && !format.equals(GRAPH_JSON_FORMAT)) { + errors.add(prefix + ", which is generated with " + format + " serialization, but '" + + sourceDescription(file) + "' is generated without (" + disabledBy(file, format) + + "). Use the same format options in both files."); + } + } + + Map options = file.getOptions(); + Map extendedOptions = extendedFile.getOptions(); + boolean visitor = !MessageGenerator.isTrue(options.get("NoVisitor"), false); + boolean extendedVisitor = !MessageGenerator.isTrue(extendedOptions.get("NoVisitor"), false); + checkSameOption(prefix, file, extendedFile, "NoVisitor", errors); + if (visitor && extendedVisitor) { + checkSameOption(prefix, file, extendedFile, "NoVisitorExceptions", errors); + } + checkSameOption(prefix, file, extendedFile, "NoTypeKind", errors); + checkSameOption(prefix, file, extendedFile, "NoInterfaces", errors); + + boolean listener = MessageGenerator.isListener(options); + boolean reflection = MessageGenerator.isReflection(options); + if (listener && !MessageGenerator.isListener(extendedOptions)) { + errors.add(prefix + ", which is generated without listener support (option NoListener), but '" + + sourceDescription(file) + "' is generated with it. Add 'option NoListener;' to '" + + sourceDescription(file) + "', or remove it from '" + sourceDescription(extendedFile) + "'."); + } else if (reflection && !MessageGenerator.isReflection(extendedOptions)) { + errors.add(prefix + ", which is generated without reflection (option NoReflection), but '" + + sourceDescription(file) + "' is generated with it. Add 'option NoReflection;' and 'option NoListener;' to '" + + sourceDescription(file) + "', or remove them from '" + sourceDescription(extendedFile) + "'."); + } + } + + private void checkSameOption(String prefix, DefinitionFile file, DefinitionFile extendedFile, String option, + List errors) { + boolean set = MessageGenerator.isTrue(file.getOptions().get(option), false); + boolean extendedSet = MessageGenerator.isTrue(extendedFile.getOptions().get(option), false); + if (set != extendedSet) { + DefinitionFile with = set ? file : extendedFile; + DefinitionFile without = set ? extendedFile : file; + errors.add(prefix + ", but only '" + sourceDescription(with) + "' declares option " + option + + ", '" + sourceDescription(without) + "' does not. Use the same setting in both files."); + } + } + + private static boolean samePackage(DefinitionFile file, DefinitionFile other) { + QName pkg = file.getPackage(); + QName otherPkg = other.getPackage(); + if (pkg == null || otherPkg == null) { + return pkg == otherPkg; + } + return pkg.getNames().equals(otherPkg.getNames()); + } + + /** + * Rejects fields whose generated names clash with the names of other fields of the same message, + * declared in the message itself or inherited from a generalization. + * + *

+ * A sub-message cannot redeclare an inherited field (not even to narrow its type), since the + * generated accessors and property constants of both declarations would clash. + *

+ */ + private void validateFieldNames(DefinitionFile file, List errors) { + for (Definition def : file.getDefinitions()) { + validateFieldNames(def, errors); + } + } + + private void validateFieldNames(Definition def, List errors) { + if (!(def instanceof MessageDef)) { + return; + } + MessageDef message = (MessageDef) def; + + // Generated names of the inherited fields, most general first. + Map inherited = new HashMap<>(); + Map owners = new HashMap<>(); + List generalizations = new ArrayList<>(); + Set seen = new HashSet<>(); + seen.add(message); + for (MessageDef current = message.getExtendedDef(); current != null && seen.add(current); current = current.getExtendedDef()) { + generalizations.add(0, current); + } + for (MessageDef generalization : generalizations) { + for (Field field : generalization.getFields()) { + owners.put(field, generalization); + for (String name : generatedNames(field)) { + inherited.putIfAbsent(name, field); + } + } + } + + Map local = new HashMap<>(); + for (Field field : message.getFields()) { + Field clash = null; + for (String name : generatedNames(field)) { + clash = local.get(name); + if (clash != null) { + break; + } + } + if (clash != null) { + errors.add(fieldError(message, field) + (clash.getName().equals(field.getName()) + ? " is declared twice. Rename or remove one of the declarations." + : " clashes with field '" + clash.getName() + "' of the same message: both generate the same Java names ('" + + CodeConvention.getterName(field) + "()', '" + CodeConvention.constant(field) + + "'). Rename one of the fields.")); + } else { + for (String name : generatedNames(field)) { + clash = inherited.get(name); + if (clash != null) { + break; + } + } + if (clash != null) { + MessageDef owner = owners.get(clash); + String origin = "'" + Util.toString(owner) + "' of '" + sourceDescription(Util.definingFile(owner)) + "'"; + errors.add(fieldError(message, field) + (clash.getName().equals(field.getName()) + ? " redeclares the field inherited from " + origin + + ". A sub-message cannot redeclare an inherited field (not even to narrow its type)." + + " Remove the declaration or rename the field." + : " clashes with field '" + clash.getName() + "' inherited from " + origin + + ": both generate the same Java names ('" + CodeConvention.getterName(field) + "()', '" + + CodeConvention.constant(field) + "'). Rename the field.")); + } + } + for (String name : generatedNames(field)) { + local.putIfAbsent(name, field); + } + } + + for (Definition inner : message.getDefinitions()) { + validateFieldNames(inner, errors); + } + } + + private String fieldError(MessageDef message, Field field) { + return sourceDescription(Util.definingFile(message)) + ": Field '" + Util.toString(message) + "." + field.getName() + "'"; + } + + /** + * The names derived from a field that must be unique among all fields of a message and its + * generalizations. + */ + private static List generatedNames(Field field) { + return Arrays.asList("suffix:" + CodeConvention.suffix(field), "constant:" + CodeConvention.constant(field)); + } + + /** + * Rejects messages of a hierarchy whose identifiers in the generated code clash. + * + *
    + *
  • The concrete specializations of an abstract message must have distinct type IDs in all + * generated formats (the JSON type ID, explicit binary type IDs and plug-in identifiers such as + * XML element names). The readers of the abstract message dispatch on these IDs (and the + * registry of an option OpenWorld hierarchy is keyed by them), so equal IDs + * produce duplicate case labels or ambiguous data.
  • + *
  • The concrete messages of a hierarchy must have distinct constants in its + * TypeKind enum, unless option NoTypeKind is given.
  • + *
  • A message must not have the name of a nested definition of one of its generalizations: + * In the generated class of the message, the name of the inherited nested class would shadow + * the name of the class itself.
  • + *
+ * + *

+ * All loaded files are considered, so that a clash of an extension with a message of another + * file of the hierarchy is found. A clash is only reported, if at least one of the messages is + * generated. + *

+ */ + private void validateHierarchyNames(GeneratorPlugin plugin, List errors) { + List messages = new ArrayList<>(); + for (DefinitionFile file : _files) { + for (Definition def : file.getDefinitions()) { + collectMessages(def, messages); + } + } + + Set reported = new HashSet<>(); + for (MessageDef message : messages) { + if (message.isAbstract()) { + validateTypeIds(message, plugin, reported, errors); + } + } + + for (MessageDef message : messages) { + if (message.getExtendedDef() == null && !message.getSpecializations().isEmpty()) { + validateTypeKinds(message, errors); + } + } + + for (MessageDef message : messages) { + if (isGenerated(message)) { + validateInheritedNames(message, errors); + } + } + } + + private static void collectMessages(Definition def, List result) { + if (def instanceof MessageDef) { + MessageDef message = (MessageDef) def; + result.add(message); + for (Definition inner : message.getDefinitions()) { + collectMessages(inner, result); + } + } + } + + private boolean isGenerated(Definition def) { + return !_importedFiles.contains(Util.definingFile(def)); + } + + private void validateTypeIds(MessageDef generalization, GeneratorPlugin plugin, Set reported, List errors) { + List specializations = new ArrayList<>(); + addConcreteSpecializations(generalization, specializations, new HashSet<>()); + List> ids = new ArrayList<>(); + for (MessageDef specialization : specializations) { + ids.add(typeIds(specialization, plugin)); + } + for (int n = 1; n < specializations.size(); n++) { + MessageDef message = specializations.get(n); + for (int m = 0; m < n; m++) { + MessageDef other = specializations.get(m); + if (!isGenerated(message) && !isGenerated(other)) { + continue; + } + List clashes = new ArrayList<>(); + Set annotations = new java.util.LinkedHashSet<>(); + boolean renameHelps = false; + for (Map.Entry entry : ids.get(n).entrySet()) { + if (!entry.getValue().equals(ids.get(m).get(entry.getKey()))) { + continue; + } + java.util.regex.Matcher matcher = TYPE_ID_KIND.matcher(entry.getKey()); + String kind = matcher.matches() ? matcher.group(1) : entry.getKey(); + if (matcher.matches()) { + annotations.add(matcher.group(2)); + } + clashes.add("the same " + kind + " '" + entry.getValue() + "'"); + renameHelps |= !entry.getKey().equals(BINARY_TYPE_ID); + } + if (clashes.isEmpty() || !reported.add(Util.protoName(other) + " " + Util.protoName(message))) { + continue; + } + MessageDef blamed = isGenerated(message) ? message : other; + errors.add(sourceDescription(Util.definingFile(blamed)) + ": In the hierarchy of '" + Util.protoName(generalization) + + "', " + describe(other) + " and " + describe(message) + " have " + + String.join(" and ", clashes) + ", so that the readers of '" + Util.protoName(generalization) + + "' cannot distinguish them. " + + (annotations.isEmpty() ? "Rename one of the messages." + : "Give one of the messages a distinct identifier with " + String.join(" or ", annotations) + + (renameHelps ? ", or rename it." : ".")) + ); + } + } + } + + /** + * Description of a type ID: the kind of identifier and the annotation that sets it. + */ + private static final java.util.regex.Pattern TYPE_ID_KIND = java.util.regex.Pattern.compile("(.*) \\((@\\w+)\\)"); + + private static final String BINARY_TYPE_ID = "binary type ID (@type_id)"; + + /** + * Adds the concrete specializations of the given message of all files in depth-first order. + */ + private static void addConcreteSpecializations(MessageDef def, List result, Set seen) { + for (MessageDef specialization : def.getSpecializations()) { + if (!seen.add(specialization)) { + continue; + } + if (!specialization.isAbstract()) { + result.add(specialization); + } + addConcreteSpecializations(specialization, result, seen); + } + } + + /** + * The identifiers of the given concrete message in polymorphic values of all generated formats, + * indexed by a description of the identifier and the annotation that sets it. + */ + private Map typeIds(MessageDef message, GeneratorPlugin plugin) { + DefinitionFile file = Util.definingFile(message); + Map options = file.getOptions(); + Map result = new java.util.LinkedHashMap<>(); + if (MessageGenerator.isJson(options) || generatesTypeScript(file)) { + result.put("type ID (@Name)", MsgBufJsonProtocol.typeId(message)); + } + if (MessageGenerator.isBinary(options)) { + Option typeId = message.getOptions().get("type_id"); + if (typeId instanceof NumberOption) { + result.put(BINARY_TYPE_ID, Integer.toString((int) ((NumberOption) typeId).getValue())); + } + } + plugin.addTypeIds(options, message, result); + return result; + } + + private String describe(Definition def) { + return "message '" + Util.protoName(def) + "' of '" + sourceDescription(Util.definingFile(def)) + "'"; + } + + /** + * Rejects clashing constants in the TypeKind enum generated for the given hierarchy + * root. + */ + private void validateTypeKinds(MessageDef root, List errors) { + DefinitionFile rootFile = Util.definingFile(root); + if (!isGenerated(root) || MessageGenerator.isTrue(rootFile.getOptions().get("NoTypeKind"), false)) { + return; + } + Map constants = new HashMap<>(); + for (MessageDef message : AbstractMessageGenerator.concreteSpecializations(root)) { + String constant = CodeConvention.typeKindConstant(message); + MessageDef clash = constants.putIfAbsent(constant, message); + if (clash != null) { + errors.add(sourceDescription(Util.definingFile(message)) + ": In the hierarchy of '" + Util.protoName(root) + + "', " + describe(clash) + " and " + describe(message) + " generate the same constant '" + constant + + "' in the enum '" + Util.toString(root) + "." + CodeConvention.TYPE_KIND_NAME + + "'. Rename one of the messages, or add 'option NoTypeKind;' to '" + sourceDescription(rootFile) + + "'" + (Util.definingFile(message) != rootFile || Util.definingFile(clash) != rootFile + ? " and all files extending its hierarchy" : "") + + "."); + } + } + } + + /** + * Rejects a message with the name of a nested definition of one of its generalizations. + */ + private void validateInheritedNames(MessageDef message, List errors) { + Set seen = new HashSet<>(); + seen.add(message); + for (MessageDef generalization = message.getExtendedDef(); generalization != null && seen.add(generalization); + generalization = generalization.getExtendedDef()) { + for (Definition member : generalization.getDefinitions()) { + if (member != message && member.getName().equals(message.getName())) { + errors.add(sourceDescription(Util.definingFile(message)) + ": Message '" + Util.protoName(message) + + "' extends message '" + Util.protoName(generalization) + "' of '" + + sourceDescription(Util.definingFile(generalization)) + "', which declares the nested " + + (member instanceof EnumDef ? "enum" : "message") + " '" + Util.protoName(member) + + "' with the same name. In the generated Java class of '" + Util.protoName(message) + + "', the name '" + message.getName() + "' would refer to the inherited nested type instead of the" + + " class itself. Rename one of them."); + return; + } + } + } + } + + /** + * Rejects references to definitions of other files that are generated without a serialization + * format that the referencing code needs. + * + *

+ * The generated read and write methods of a message call the corresponding methods of the + * messages and enums of its fields and of its generalization. If one of these is defined in + * another file that disables the format, the generated code would not compile. + *

+ */ + private void validateFormatReferences(DefinitionFile file, GeneratorPlugin plugin, List errors) { + for (Definition def : file.getDefinitions()) { + validateFormatReferences(file, def, plugin, errors); + } + } + + private void validateFormatReferences(DefinitionFile file, Definition def, GeneratorPlugin plugin, List errors) { + if (!(def instanceof MessageDef)) { + return; + } + MessageDef message = (MessageDef) def; + Set formats = formats(file, plugin); + + MessageDef extended = message.getExtendedDef(); + if (extended != null) { + checkFormats(file, formats, "Message '" + Util.toString(message) + "' extends", extended, plugin, errors); + } + + for (Field field : message.getFields()) { + Set fieldFormats = fieldFormats(file, field, plugin); + for (Definition target : referencedDefinitions(field.getType())) { + checkFormats(file, fieldFormats, + "Field '" + Util.toString(message) + "." + field.getName() + "' references", target, plugin, errors); + } + } + + for (Definition inner : message.getDefinitions()) { + validateFormatReferences(file, inner, plugin, errors); + } + } + + private void checkFormats(DefinitionFile file, Set formats, String reference, Definition target, + GeneratorPlugin plugin, List errors) { + DefinitionFile targetFile = Util.definingFile(target); + if (targetFile == file) { + return; + } + boolean isEnum = target instanceof EnumDef; + Set targetFormats = isEnum ? enumFormats(targetFile.getOptions()) : formats(targetFile, plugin); + String prefix = sourceDescription(file) + ": " + reference + (isEnum ? " enum '" : " message '") + + Util.toString(target) + "' of '" + sourceDescription(targetFile) + "'"; + for (String format : formats) { + if (isEnum) { + if (format.equals(GRAPH_JSON_FORMAT)) { + // The JSON methods of an enum do not depend on the graph mode. + format = JSON_FORMAT; + } else if (!format.equals(JSON_FORMAT) && !format.equals(BINARY_FORMAT)) { + // Enums are serialized in plug-in formats through their protocol names. + continue; + } + } + if (targetFormats.contains(format)) { + continue; + } + if (format.equals(GRAPH_JSON_FORMAT) || (format.equals(JSON_FORMAT) && targetFormats.contains(GRAPH_JSON_FORMAT))) { + errors.add(prefix + ", but only one of the files uses option SharedGraph. Use option SharedGraph in both" + + " files or in neither."); + } else { + errors.add(prefix + ", which is generated without " + format + " serialization (" + + disabledBy(targetFile, format) + "). Add 'option " + DISABLE_OPTION.get(format) + ";' to '" + + sourceDescription(file) + "', or enable " + format + " serialization in '" + + sourceDescription(targetFile) + "'."); + } + } + } + + private static final String JSON_FORMAT = "JSON"; + + /** + * JSON of the SharedGraph mode, which has its own read and write methods. + */ + private static final String GRAPH_JSON_FORMAT = "SharedGraph JSON"; + + private static final String BINARY_FORMAT = "binary"; + + private static final Map DISABLE_OPTION = + Map.of(JSON_FORMAT, "NoJson", BINARY_FORMAT, "NoBinary", XmlStreamingPlugin.XML_FORMAT, "NoXml"); + + private static Set formats(DefinitionFile file, GeneratorPlugin plugin) { + Set result = coreFormats(file.getOptions()); + plugin.addFormats(file.getOptions(), result); + return result; + } + + private static Set fieldFormats(DefinitionFile file, Field field, GeneratorPlugin plugin) { + Set result = new HashSet<>(); + if (!field.isTransient() && !field.isDerived()) { + result.addAll(coreFormats(file.getOptions())); + } + plugin.addFieldFormats(file.getOptions(), field, result); + return result; + } + + /** + * The formats of the generated read and write methods of messages. + */ + private static Set coreFormats(Map options) { + Set result = new HashSet<>(); + if (MessageGenerator.isJson(options)) { + result.add(MessageGenerator.isTrue(options.get("SharedGraph"), false) ? GRAPH_JSON_FORMAT : JSON_FORMAT); + } + if (MessageGenerator.isBinary(options)) { + result.add(BINARY_FORMAT); + } + return result; + } + + /** + * The formats of the generated read and write methods of enums. + */ + private static Set enumFormats(Map options) { + Set result = new HashSet<>(); + if (MessageGenerator.isJson(options)) { + result.add(JSON_FORMAT); + } + if (MessageGenerator.isBinary(options)) { + result.add(BINARY_FORMAT); + } + return result; + } + + private static String disabledBy(DefinitionFile file, String format) { + if (format.equals(BINARY_FORMAT)) { + if (Util.getFlag(file, "SharedGraph")) { + return "option SharedGraph"; + } + if (Util.getFlag(file, "OpenWorld")) { + return "option OpenWorld implies NoBinary"; + } + } + return "option " + DISABLE_OPTION.get(format); + } + + private static List referencedDefinitions(Type type) { + List result = new ArrayList<>(); + type.visit(new Type.Visitor() { + @Override + public Void visit(CustomType self, Void arg) { + if (self.getDefinition() != null) { + result.add(self.getDefinition()); + } + return null; + } + + @Override + public Void visit(PrimitiveType self, Void arg) { + return null; + } + + @Override + public Void visit(MapType self, Void arg) { + self.getKeyType().visit(this, arg); + self.getValueType().visit(this, arg); + return null; + } + }, null); + return result; + } + private void resolveImports(DefinitionFile file, File sourceFile) throws IOException, ParseException { for (String importPath : file.getImports()) { // Try file system first @@ -332,6 +1024,7 @@ private void resolveImports(DefinitionFile file, File sourceFile) throws IOExcep if (resolved != null) { String canonical = resolved.getCanonicalPath(); if (_loadedFiles.contains(canonical)) { + addImport(file, _fileByPath.get(canonical)); continue; } _loadedFiles.add(canonical); @@ -339,6 +1032,8 @@ private void resolveImports(DefinitionFile file, File sourceFile) throws IOExcep try (InputStream in = new FileInputStream(resolved)) { imported = parse(in); } + _fileByPath.put(canonical, imported); + addImport(file, imported); _sourceNames.put(imported, resolved.getName()); _files.add(imported); _table.enter(imported); @@ -351,6 +1046,7 @@ private void resolveImports(DefinitionFile file, File sourceFile) throws IOExcep if (_importClassLoader != null) { String resourceKey = "classpath:" + importPath; if (_loadedFiles.contains(resourceKey)) { + addImport(file, _fileByPath.get(resourceKey)); continue; } InputStream classpathStream = _importClassLoader.getResourceAsStream(importPath); @@ -360,6 +1056,8 @@ private void resolveImports(DefinitionFile file, File sourceFile) throws IOExcep try (InputStream in = classpathStream) { imported = parse(in); } + _fileByPath.put(resourceKey, imported); + addImport(file, imported); _sourceNames.put(imported, new File(importPath).getName()); _files.add(imported); _table.enter(imported); @@ -374,10 +1072,17 @@ private void resolveImports(DefinitionFile file, File sourceFile) throws IOExcep } } + private void addImport(DefinitionFile file, DefinitionFile imported) { + if (imported != null && imported != file) { + _table.addImport(file, imported); + } + } + private void resolveImportsFromClasspath(DefinitionFile file) throws IOException, ParseException { for (String importPath : file.getImports()) { String resourceKey = "classpath:" + importPath; if (_loadedFiles.contains(resourceKey)) { + addImport(file, _fileByPath.get(resourceKey)); continue; } @@ -389,6 +1094,8 @@ private void resolveImportsFromClasspath(DefinitionFile file) throws IOException try (InputStream in = classpathStream) { imported = parse(in); } + _fileByPath.put(resourceKey, imported); + addImport(file, imported); _sourceNames.put(imported, new File(importPath).getName()); _files.add(imported); _table.enter(imported); @@ -489,14 +1196,21 @@ private List findCrossFileExtensions(DefinitionFile file) { return result; } + /** + * Collects the concrete messages of the given file that must be registered with the registry of + * an option OpenWorld hierarchy. + * + *

+ * These are all concrete messages with a generalization defined in another file with + * option OpenWorld. The readers of this generalization (and of its generalizations) + * only find these types through the registry of the hierarchy root. This includes messages + * that extend a message of the same file that extends a message of another file, and messages + * that extend a message of an extension file. + *

+ */ private void collectCrossFileExtensions(MessageDef def, DefinitionFile file, List result) { - MessageDef extended = def.getExtendedDef(); - if (extended != null && extended.getFile() != file) { - if (Util.getFlag(extended.getFile(), "OpenWorld")) { - if (!def.isAbstract()) { - result.add(def); - } - } + if (!def.isAbstract() && hasOpenWorldGeneralizationInOtherFile(def, file)) { + result.add(def); } for (Definition inner : def.getDefinitions()) { if (inner instanceof MessageDef) { @@ -505,7 +1219,27 @@ private void collectCrossFileExtensions(MessageDef def, DefinitionFile file, Lis } } - private String generateRegistrationClass(DefinitionFile file, List extensions) { + private static boolean hasOpenWorldGeneralizationInOtherFile(MessageDef def, DefinitionFile file) { + Set seen = new HashSet<>(); + for (MessageDef current = def.getExtendedDef(); current != null && seen.add(current); current = current.getExtendedDef()) { + DefinitionFile currentFile = Util.definingFile(current); + if (currentFile != file && Util.getFlag(currentFile, "OpenWorld")) { + return true; + } + } + return false; + } + + private static MessageDef hierarchyRoot(MessageDef def) { + Set seen = new HashSet<>(); + MessageDef result = def; + while (result.getExtendedDef() != null && seen.add(result)) { + result = result.getExtendedDef(); + } + return result; + } + + private String generateRegistrationClass(DefinitionFile file, List extensions, GeneratorPlugin plugin) { String packageName = CodeConvention.packageName(file.getPackage()); String[] parts = packageName.split("\\."); String baseName = parts[parts.length - 1]; @@ -514,6 +1248,8 @@ private String generateRegistrationClass(DefinitionFile file, List e File dir = mkdir(file.getPackage()); File out = new File(dir, className + ".java"); + boolean xml = formats(file, plugin).contains(XmlStreamingPlugin.XML_FORMAT); + try (FileOutputStream os = new FileOutputStream(out)) { try (PrintWriter w = new PrintWriter(new OutputStreamWriter(os, "utf-8"))) { System.out.println("Generating '" + out + "'."); @@ -527,15 +1263,17 @@ private String generateRegistrationClass(DefinitionFile file, List e w.println("\t@Override"); w.println("\tpublic void register() {"); for (MessageDef ext : extensions) { - // Find the OpenWorld root type - MessageDef root = ext.getExtendedDef(); - while (root.getExtendedDef() != null) { - root = root.getExtendedDef(); - } + MessageDef root = hierarchyRoot(ext); String rootQName = CodeConvention.qTypeName(root); String extQName = CodeConvention.qTypeName(ext); String typeConstant = CodeConvention.jsonTypeConstant(ext); w.println("\t\t" + rootQName + ".register(" + extQName + "." + typeConstant + ", " + extQName + "::create);"); + if (xml && formats(Util.definingFile(root), plugin).contains(XmlStreamingPlugin.XML_FORMAT)) { + // The XML readers of the hierarchy dispatch unknown element names through the registry of the root. + String extImplQName = CodeConvention.qImplName(CodeConvention.IMPL_PACKAGE_SUFFIX, ext); + w.println("\t\t" + rootQName + "." + XmlStreamingPlugin.REGISTER_XML + "(" + extImplQName + "." + + XmlStreamingPlugin.xmlElementConstant(ext) + ", " + extQName + "::create);"); + } } w.println("\t}"); w.println(); @@ -600,7 +1338,7 @@ public PackageGenerator(File dir, Map options, GeneratorPlugin p @Override public Void visit(EnumDef def, Void arg) { - return generateJava(CodeConvention.typeName(def), null, new EnumGenerator(def)); + return generateJava(CodeConvention.typeName(def), null, new EnumGenerator(_options, def)); } @Override @@ -702,7 +1440,14 @@ public static void main(String... args) throws ParseException, IOException, Inst generator.setOut(out); } - generator.generate(loadPlugins()); + try { + generator.generate(loadPlugins()); + } catch (GeneratorException ex) { + for (String error : ex.getErrors()) { + System.err.println("ERROR: " + error); + } + System.exit(1); + } } /** diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/GeneratorException.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/GeneratorException.java new file mode 100644 index 00000000..7df8fecb --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/GeneratorException.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2026 Bernhard Haumacher et al. All Rights Reserved. + */ +package de.haumacher.msgbuf.generator; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Rejection of the input definitions: code generation was not started, because the definitions + * are invalid. + */ +public class GeneratorException extends RuntimeException { + + private final List _errors; + + /** + * Creates a {@link GeneratorException}. + * + * @param errors + * The problems found, each naming the file and the definition concerned. + */ + public GeneratorException(List errors) { + super(String.join("\n", errors)); + _errors = Collections.unmodifiableList(new ArrayList<>(errors)); + } + + /** + * The problems found, each naming the file and the definition concerned. + */ + public List getErrors() { + return _errors; + } + +} diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/GeneratorPlugin.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/GeneratorPlugin.java index b27322bb..a96b1fed 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/GeneratorPlugin.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/GeneratorPlugin.java @@ -5,7 +5,9 @@ import java.util.List; import java.util.Map; +import java.util.Set; +import de.haumacher.msgbuf.generator.ast.Field; import de.haumacher.msgbuf.generator.ast.MessageDef; import de.haumacher.msgbuf.generator.ast.Option; import de.haumacher.msgbuf.generator.util.FileGenerator; @@ -58,6 +60,67 @@ default FileGenerator messageImplContents(Map options, MessageDe return (out, indent) -> {/*ignore*/}; } + /** + * Adds the names of the serialization formats this plug-in generates code for. + * + *

+ * A message referencing a message of another file requires all formats of its own file in the + * other file, since its generated code calls the other message's generated read and write + * methods. + *

+ * + * @param options + * The options of a definition file. + * @param formats + * The set of format names to add to. + */ + default void addFormats(Map options, Set formats) { + // No additional formats by default. + } + + /** + * Adds the names of the serialization formats in which the code generated by this plug-in + * writes and reads the value of the given field. + * + *

+ * If the field references a message or enum of another file, that file must generate code for + * these formats. + *

+ * + * @param options + * The options of the file defining the field. + * @param field + * The field to check. + * @param formats + * The set of format names to add to. + * + * @see #addFormats(Map, Set) + */ + default void addFieldFormats(Map options, Field field, Set formats) { + // No additional formats by default. + } + + /** + * Adds the identifiers of the given concrete message in polymorphic values of the formats of + * this plug-in. + * + *

+ * The generator rejects two concrete specializations of an abstract message with the same + * identifier, since the readers of the abstract message cannot distinguish them. + *

+ * + * @param options + * The options of the file defining the message. + * @param def + * The concrete message. + * @param typeIds + * The identifiers to add to, indexed by a description of the identifier that names the + * annotation that sets it, e.g. "XML element name (@XmlName)". + */ + default void addTypeIds(Map options, MessageDef def, Map typeIds) { + // No additional identifiers by default. + } + /** * {@link GeneratorPlugin} that does not generate any output. */ @@ -88,6 +151,24 @@ public void addInterfaces(Map options, MessageDef def, List options, Set formats) { + self.addFormats(options, formats); + next.addFormats(options, formats); + } + + @Override + public void addFieldFormats(Map options, Field field, Set formats) { + self.addFieldFormats(options, field, formats); + next.addFieldFormats(options, field, formats); + } + + @Override + public void addTypeIds(Map options, MessageDef def, Map typeIds) { + self.addTypeIds(options, def, typeIds); + next.addTypeIds(options, def, typeIds); + } @Override public FileGenerator messageImplContents(Map options, MessageDef def) { diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java index d3d7abd4..d4578e31 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java @@ -17,6 +17,7 @@ import de.haumacher.msgbuf.binary.DataType; import de.haumacher.msgbuf.generator.ast.CustomType; import de.haumacher.msgbuf.generator.ast.Definition; +import de.haumacher.msgbuf.generator.ast.DefinitionFile; import de.haumacher.msgbuf.generator.ast.EnumDef; import de.haumacher.msgbuf.generator.ast.Field; import de.haumacher.msgbuf.generator.ast.MapType; @@ -65,10 +66,10 @@ public MessageGenerator(NameTable table, Map options, boolean is _plugin = plugin; _defaultValues = new DefaultValueGenerator(options); _graph = isTrue(options.get("SharedGraph"), false); - _json = _graph || !isTrue(options.get("NoJson"), false); - _binary = !_graph && !isTrue(options.get("NoBinary"), false); - _listener = _graph || !isTrue(options.get("NoListener"), false); - _reflection = _listener || !isTrue(options.get("NoReflection"), false); + _json = isJson(options); + _binary = isBinary(options); + _listener = isListener(options); + _reflection = isReflection(options); _visitor = !isTrue(options.get("NoVisitor"), false); _visitEx= !isTrue(options.get("NoVisitorExceptions"), false); _typeKind = !isTrue(options.get("NoTypeKind"), false); @@ -268,7 +269,7 @@ private void generateClassContents() { if (_visitor) { generateVisitorInterface(); } - if (isCrossFileExtension() && !_def.isAbstract() && (_interface || _noInterfaces)) { + if (_visitor && isCrossFileExtension() && !_def.isAbstract() && (_interface || _noInterfaces)) { generateExtensionVisitorInterface(); } } @@ -433,10 +434,38 @@ private void generateInnerDefinitions() { } } + /** + * Whether listener support is generated for the given file options. + */ + public static boolean isListener(Map options) { + return isTrue(options.get("SharedGraph"), false) || !isTrue(options.get("NoListener"), false); + } + + /** + * Whether reflective property access is generated for the given file options. + */ + public static boolean isReflection(Map options) { + return isListener(options) || !isTrue(options.get("NoReflection"), false); + } + + /** + * Whether JSON serialization code is generated for the given file options. + */ + public static boolean isJson(Map options) { + return isTrue(options.get("SharedGraph"), false) || !isTrue(options.get("NoJson"), false); + } + + /** + * Whether binary serialization code is generated for the given file options. + */ + public static boolean isBinary(Map options) { + return !isTrue(options.get("SharedGraph"), false) && !isTrue(options.get("NoBinary"), false); + } + @Override public Void visit(EnumDef def, Void arg) { if (_interface || _noInterfaces) { - include(new EnumGenerator(def)); + include(new EnumGenerator(getOptions(), def)); } return null; } @@ -649,8 +678,8 @@ private void generateKindLookup() { kindLookupComment(); line("public abstract " + TYPE_KIND_NAME + " kind();"); } - } else if (isCrossFileExtension()) { - // Cross-file extensions are not in the base's TypeKind enum, return null + } else if (isOpenWorldExtension()) { + // Types of other files are not in the TypeKind enum of an OpenWorld root, return null nl(); line("@Override"); line("public " + TYPE_KIND_NAME + " kind() {"); @@ -1359,11 +1388,26 @@ private void generateJson() { if (isOpenWorld()) { line("default: {"); { - line("de.haumacher.msgbuf.data.Factory factory = " + getOpenWorldRoot() + ".REGISTRY.get(type);"); - line("if (factory != null) {"); - { - line("result = factory.create();"); - line("result.readContent(in);"); + // Types of other files are only known through the registry of the hierarchy root, + // which is filled by the registrations found on the class path. + line("de.haumacher.msgbuf.data.TypeRegistryLoader.ensureLoaded();"); + String root = getOpenWorldRoot(); + if (_def.getExtendedDef() == null) { + line("de.haumacher.msgbuf.data.Factory factory = " + root + ".REGISTRY.get(type);"); + line("if (factory != null) {"); + { + line("result = factory.create();"); + line("result.readContent(in);"); + } + } else { + // The registry of the root may contain types that are no specializations of this type. + line("de.haumacher.msgbuf.data.Factory factory = " + root + ".REGISTRY.get(type);"); + line(root + " instance = factory == null ? null : factory.create();"); + line("if (instance instanceof " + thisType() + ") {"); + { + line("result = (" + thisType() + ") instance;"); + line("result.readContent(in);"); + } } line("} else {"); { @@ -1846,8 +1890,12 @@ private void binaryWrite() { continue; } boolean nullable = Util.isNullable(field); + // The default value of a bytes field is null, which cannot be written. + boolean nullBytes = !nullable && Util.isSingleBytes(field); if (nullable) { line("if (" + hasName(field) + "()" + ") {"); + } else if (nullBytes) { + line("if (" + getterCall(field) + " != null) {"); } { line("out.name(" + binaryConstant(field) + ");"); @@ -1868,7 +1916,7 @@ private void binaryWrite() { binaryWriteValue(field.getType(), getterCall(field)); } } - if (nullable) { + if (nullable || nullBytes) { line("}"); } } @@ -1880,10 +1928,24 @@ private void binaryWrite() { private void binaryWriteValue(Type type, String x) { if (type instanceof PrimitiveType) { - if (((PrimitiveType) type).getKind() == Kind.JSON) { - line("de.haumacher.msgbuf.json.JsonUtil.toJsonValue(" + x + ").writeTo(out);"); - } else { - line("out.value(" + x + ");"); + switch (((PrimitiveType) type).getKind()) { + case JSON: + line("de.haumacher.msgbuf.json.JsonUtil.toJsonValue(" + x + ").writeTo(out);"); + break; + case SINT_32: + case SINT_64: + // Zig-zag encoding, as read by mkBinaryReadValue() and announced by mkBinaryType(). + line("out.valueSigned(" + x + ");"); + break; + case FIXED_32: + case SFIXED_32: + case FIXED_64: + case SFIXED_64: + // Fixed-length encoding, as read by mkBinaryReadValue() and announced by mkBinaryType(). + line("out.valueFixed(" + x + ");"); + break; + default: + line("out.value(" + x + ");"); } } else if (type instanceof CustomType) { line(x + ".writeTo(out);"); @@ -2200,7 +2262,17 @@ private void generateVisitMethods() { line("public" + (_def.isAbstract() ? " final" : "") + " R visit(" + qTypeName(gen) + ".Visitor v, A arg) " + onVisitEx("throws E ") + "{"); { if (_def.isAbstract()) { - line("return visit((" + qTypeName(_def) + ".Visitor) v, arg);"); + if (isCrossFileExtension()) { + // The visitor of the generalization does not know this type. + line("if (v instanceof " + qTypeName(_def) + ".Visitor) {"); + { + line("return visit((" + qTypeName(_def) + ".Visitor) v, arg);"); + } + line("}"); + line("return v.visitDefault(this, arg);"); + } else { + line("return visit((" + qTypeName(_def) + ".Visitor) v, arg);"); + } } else if (isCrossFileExtension()) { line("if (v instanceof " + qTypeName(_def) + ".Visitor) {"); { @@ -2345,11 +2417,27 @@ private String getOpenWorldRoot() { private boolean isCrossFileExtension() { MessageDef gen = getAbstractGeneralization(); if (gen == null) return false; - return gen.getFile() != _def.getFile() && Util.getFlag(gen.getFile(), "OpenWorld"); + DefinitionFile genFile = Util.definingFile(gen); + return genFile != Util.definingFile(_def) && Util.getFlag(genFile, "OpenWorld"); + } + + /** + * Whether the generated type belongs to an OpenWorld hierarchy whose root is defined in + * another file. + * + *

+ * Such a type is not known to the root, e.g. it is not listed in the root's TypeKind enum. + * In contrast to {@link #isCrossFileExtension()}, this also holds for a type that extends a + * message of its own file which in turn extends a message of another file. + *

+ */ + private boolean isOpenWorldExtension() { + DefinitionFile rootFile = Util.definingFile(getRoot(_def)); + return rootFile != Util.definingFile(_def) && Util.getFlag(rootFile, "OpenWorld"); } private List localSpecializations(MessageDef def) { - return localSpecializations(def, _def.getFile()); + return localSpecializations(def, Util.definingFile(_def)); } } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/NameTable.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/NameTable.java index 0b74a64c..77534f74 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/NameTable.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/NameTable.java @@ -3,10 +3,14 @@ */ package de.haumacher.msgbuf.generator; +import java.util.ArrayList; +import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.function.Function; +import java.util.stream.Collectors; import de.haumacher.msgbuf.generator.ast.Constant; import de.haumacher.msgbuf.generator.ast.Definition; @@ -15,36 +19,59 @@ import de.haumacher.msgbuf.generator.ast.Field; import de.haumacher.msgbuf.generator.ast.MessageDef; import de.haumacher.msgbuf.generator.ast.QName; +import de.haumacher.msgbuf.generator.common.Util; /** - * TODO + * Index of all definitions of the files processed together, resolving type names. + * + *

+ * A name is resolved in the context of the message it is used in, see + * {@link #resolve(DefinitionFile, MessageDef, QName)}. + *

*/ public class NameTable implements Definition.Visitor { - + private final Map _packageByName = new HashMap<>(); - private final Map _definitionByName = new HashMap<>(); - + + /** + * The files imported by a file (its import declarations), in declaration order. + */ + private final Map> _imports = new HashMap<>(); + + /** + * Errors to report, formatted with a function describing the source of a file. + */ + private final List, String>> _errors = new ArrayList<>(); + public void enter(DefinitionFile file) { Package pkg = mkPackage(file.getPackage()); - + for (Definition def : file.getDefinitions()) { pkg.enter(file, def); def.visit(this, null); } } - + + /** + * Records that the given file imports the other file. + */ + public void addImport(DefinitionFile file, DefinitionFile imported) { + List list = _imports.computeIfAbsent(file, x -> new ArrayList<>()); + if (!list.contains(imported)) { + list.add(imported); + } + } + @Override public Void visit(EnumDef self, Void arg) { - enterDef(self); for (Constant part : self.getConstants()) { part.setOwner(self); } return null; } - + @Override public Void visit(MessageDef self, Void arg) { - enterDef(self); for (Field part : self.getFields()) { part.setOwner(self); } @@ -55,19 +82,8 @@ public Void visit(MessageDef self, Void arg) { return null; } - private void enterDef(Definition def) { - if (def.getOuter() == null) { - _definitionByName.put(def.getName(), def); - } - } - private Package mkPackage(QName qName) { - String name; - if (qName == null) { - name = ""; - } else { - name = CodeConvention.packageName(qName); - } + String name = packageName(qName); Package result = _packageByName.get(name); if (result == null) { result = new Package(name); @@ -76,13 +92,17 @@ private Package mkPackage(QName qName) { return result; } + private static String packageName(QName qName) { + return qName == null ? "" : CodeConvention.packageName(qName); + } + class Package { - + private final String _name; - + private final Map _definitionsByName = new HashMap<>(); - /** + /** * Creates a {@link Package}. */ public Package(String name) { @@ -92,33 +112,56 @@ public Package(String name) { public String getName() { return _name; } - - /** - * TODO - * @param file + + /** + * Enters the given top-level definition of the given file. */ public void enter(DefinitionFile file, Definition def) { def.setFile(file); - Definition clash = _definitionsByName.put(def.getName(), def); + Definition clash = _definitionsByName.putIfAbsent(def.getName(), def); if (clash != null) { - error("Duplicate definition '" + def.getName() + "' in package '" + getName() + "'."); + String qName = (getName().isEmpty() ? "" : getName() + ".") + def.getName(); + DefinitionFile clashFile = clash.getFile(); + _errors.add(source -> source.apply(file) + ": Duplicate definition of '" + qName + "'" + + (clashFile == file + ? ". Rename or remove one of the definitions." + : ", it is also defined in '" + source.apply(clashFile) + + "'. Rename one of the definitions, or do not pass both files to the generator.")); } } } - /** - * TODO + /** + * Reports the errors found so far (duplicate definitions and ambiguous names) and forgets them. + * + * @param source + * Function describing the source of a file in error messages. + * @return The error messages. + */ + public List drainErrors(Function source) { + List result = _errors.stream().map(e -> e.apply(source)).collect(Collectors.toList()); + _errors.clear(); + return result; + } + + /** + * Reports a problem that does not stop the generation. */ public void error(String message) { System.err.println(message); } /** - * TODO + * Resolves the given name used in the given message and reports an error, if the name cannot + * be resolved. + * + * @see #resolve(DefinitionFile, MessageDef, QName) */ public Definition lookup(MessageDef context, QName name) { - Definition result = resolve(context, name); - if (result == null) { + DefinitionFile file = context == null ? null : Util.definingFile(context); + int errorCount = _errors.size(); + Definition result = resolve(file, context, name, true); + if (result == null && _errors.size() == errorCount) { error("Name cannot be resolved" + (context == null ? "" : " in '" + context.getName() + "'") + ": " + CodeConvention.qTypeName(name)); } return result; @@ -132,13 +175,53 @@ public Definition lookup(MessageDef context, QName name) { * @param name * The name to resolve. * @return The resolved definition, or null if the name cannot be resolved. + * + * @see #resolve(DefinitionFile, MessageDef, QName) */ public Definition resolve(MessageDef context, QName name) { - String baseName = name.getNames().get(0); + return resolve(context == null ? null : Util.definingFile(context), context, name); + } - Definition base = lookupBase(context, baseName); + /** + * Resolves the given name in the given context without reporting an error. + * + *

+ * The first part of the name is resolved as follows: + *

+ *
    + *
  1. A nested definition of the context message or one of its outer messages.
  2. + *
  3. A top-level definition of the package of the given file (in any of the files processed + * together).
  4. + *
  5. A top-level definition of a file imported by the given file, if it is unique among these + * files. If none of them defines the name, the files imported by these files, and so on.
  6. + *
  7. For compatibility, a top-level definition of any other file processed together, if it is + * unique.
  8. + *
+ *

+ * The remaining parts are resolved as nested definitions. If this fails, the name is resolved as + * a package-qualified name. + *

+ * + * @param file + * The file in which the name is used, null if unknown. + * @param context + * The message in which the name is used, null for top-level usage. + * @param name + * The name to resolve. + * @return The resolved definition, or null if the name cannot be resolved (or is + * ambiguous). + */ + public Definition resolve(DefinitionFile file, MessageDef context, QName name) { + return resolve(file, context, name, false); + } - if (base != null) { + private Definition resolve(DefinitionFile file, MessageDef context, QName name, boolean report) { + String baseName = name.getNames().get(0); + + boolean[] fromImports = { false }; + List candidates = lookupBase(file, context, baseName, fromImports); + if (candidates.size() == 1) { + Definition base = candidates.get(0); // Try resolving remaining parts as inner definitions boolean resolved = true; for (int n = 1; n < name.getNames().size(); n++) { @@ -175,9 +258,29 @@ public Definition resolve(MessageDef context, QName name) { } } + if (report && candidates.size() > 1) { + String usage = context == null ? "" : " in '" + Util.protoName(context) + "'"; + String pkgName = file == null ? null : packageName(file.getPackage()); + _errors.add(source -> (file == null ? "" : source.apply(file) + ": ") + "The name '" + + CodeConvention.qTypeName(name) + "'" + usage + " is ambiguous, it could refer to " + + candidates.stream().map(c -> "'" + Util.protoName(c) + "' of '" + source.apply(c.getFile()) + "'") + .collect(Collectors.joining(" and ")) + + (pkgName == null ? "" + : fromImports[0] + ? ", which are defined in files imported by '" + source.apply(file) + "', and " + + packageDescription(pkgName) + " does not define this name" + : ". Neither " + packageDescription(pkgName) + " nor the files imported by '" + source.apply(file) + + "' define this name, and the candidates are defined in files that are not imported, but" + + " generated together") + + ". Use a qualified name, e.g. '" + Util.protoName(candidates.get(0)) + "'."); + } return null; } + private static String packageDescription(String pkgName) { + return pkgName.isEmpty() ? "the default package" : "package '" + pkgName + "'"; + } + private Definition lookupInner(Definition base, String nextName) { if (base instanceof MessageDef) { Optional match = ((MessageDef) base).getDefinitions().stream().filter(d -> nextName.equals(d.getName())).findFirst(); @@ -191,15 +294,70 @@ private Definition lookupInner(Definition base, String nextName) { } } - private Definition lookupBase(MessageDef context, String baseName) { + /** + * The candidates for the first part of a name. + * + * @param fromImports + * Output: whether the result consists of definitions of imported files. + * @return A single definition, if the name is resolved, more than one, if the name is + * ambiguous. + */ + private List lookupBase(DefinitionFile file, MessageDef context, String baseName, boolean[] fromImports) { while (context != null) { Definition inner = lookupInner(context, baseName); if (inner != null) { - return inner; + return List.of(inner); } context = context.getOuter(); } - - return _definitionByName.get(baseName); + + if (file != null) { + Package pkg = _packageByName.get(packageName(file.getPackage())); + Definition local = pkg == null ? null : pkg._definitionsByName.get(baseName); + if (local != null) { + return List.of(local); + } + + // Definitions of the files imported directly, then of the files imported by these, and so on. + java.util.Set seen = new java.util.HashSet<>(); + seen.add(file); + List level = List.of(file); + while (!level.isEmpty()) { + List next = new ArrayList<>(); + for (DefinitionFile current : level) { + for (DefinitionFile imported : _imports.getOrDefault(current, List.of())) { + if (seen.add(imported)) { + next.add(imported); + } + } + } + List found = new ArrayList<>(); + for (DefinitionFile imported : next) { + for (Definition def : imported.getDefinitions()) { + if (def.getName().equals(baseName) && !found.contains(def)) { + found.add(def); + } + } + } + if (!found.isEmpty()) { + fromImports[0] = true; + found.sort(Comparator.comparing(Util::protoName)); + return found; + } + level = next; + } + } + + // For compatibility, a definition of a file that is not imported can be referenced by its + // simple name, if it is unique among all files processed together. + List global = new ArrayList<>(); + for (Package pkg : _packageByName.values()) { + Definition def = pkg._definitionsByName.get(baseName); + if (def != null) { + global.add(def); + } + } + global.sort(Comparator.comparing(Util::protoName)); + return global; } } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/common/Util.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/common/Util.java index f2ace617..bf302b36 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/common/Util.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/common/Util.java @@ -11,6 +11,7 @@ import de.haumacher.msgbuf.generator.CodeConvention; import de.haumacher.msgbuf.generator.ast.CustomType; import de.haumacher.msgbuf.generator.ast.Definition; +import de.haumacher.msgbuf.generator.ast.DefinitionFile; import de.haumacher.msgbuf.generator.ast.EnumDef; import de.haumacher.msgbuf.generator.ast.Field; import de.haumacher.msgbuf.generator.ast.Flag; @@ -45,6 +46,24 @@ public static String stringContent(String stringLiteral) { return stringLiteral.substring(1, stringLiteral.length() - 1).replaceAll("\\\\(.)", "$1"); } + /** + * The file the given definition is declared in. + * + *

+ * Only top-level definitions have a direct reference to their file ({@link Definition#getFile()} + * is null for nested definitions, which marks them as nested for name + * qualification). For a nested definition, the file of its top-level outer definition is + * returned. + *

+ */ + public static DefinitionFile definingFile(Definition def) { + Definition current = def; + while (current.getOuter() != null) { + current = current.getOuter(); + } + return current.getFile(); + } + public static String toString(Definition def) { MessageDef outer = def.getOuter(); if (outer == null) { @@ -59,6 +78,22 @@ public static String toString(Definition def) { } } + /** + * The name of the given definition qualified with its package and outer messages, as written in + * the .proto file. + */ + public static String protoName(Definition def) { + List names = new ArrayList<>(); + for (Definition current = def; current != null; current = current.getOuter()) { + names.add(0, current.getName()); + } + QName pkg = definingFile(def).getPackage(); + if (pkg != null) { + names.addAll(0, pkg.getNames()); + } + return String.join(".", names); + } + public static String toString(Part part) { return toString(part.getOwner()) + "#" + part.getName(); } @@ -76,6 +111,19 @@ public static boolean isNullable(Field field) { return getFlag(field, "Nullable") || (!field.isRepeated() && isNullable(field.getType())); } + /** + * Whether the given field is a single (not repeated) bytes field. + * + *

+ * The default value of such field is null, even if the field is not nullable. + *

+ */ + public static boolean isSingleBytes(Field field) { + Type type = field.getType(); + return !field.isRepeated() && type instanceof PrimitiveType + && ((PrimitiveType) type).getKind() == PrimitiveType.Kind.BYTES; + } + public static boolean isNullable(Type type) { if (type instanceof PrimitiveType) { return ((PrimitiveType) type).getKind() == PrimitiveType.Kind.JSON; diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java index 29ab65c0..8d1890a7 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java @@ -32,6 +32,13 @@ * {@link GeneratorPlugin} generating XML reading code for the {@link javax.xml.stream.XMLStreamReader} interface. */ public class XmlStreamingPlugin implements GeneratorPlugin { + + /** + * Name of the XML format. + * + * @see #addFormats(Map, Set) + */ + public static final String XML_FORMAT = "XML"; private boolean _noXmlNames; @@ -40,6 +47,41 @@ public void init(Map options) { _noXmlNames = noXmlNames(options); } + @Override + public void addFormats(Map options, Set formats) { + if (!noXml(options)) { + formats.add(XML_FORMAT); + } + } + + @Override + public void addFieldFormats(Map options, Field field, Set formats) { + // Maps are not supported in XML. + if (!noXml(options) && xmlSerialized(field) && field.getType().kind() != Type.TypeKind.MAP_TYPE) { + formats.add(XML_FORMAT); + } + } + + /** + * Whether the given field is written and read in XML format. + * + *

+ * Like in JSON and binary format, transient and derived fields (container and reverse + * references) are not serialized. Readers skip such attributes and elements in documents of + * earlier versions. + *

+ */ + static boolean xmlSerialized(Field field) { + return !field.isTransient() && !field.isDerived(); + } + + @Override + public void addTypeIds(Map options, MessageDef def, Map typeIds) { + if (!noXml(options)) { + typeIds.put("XML element name (@XmlName)", xmlTypeName(def, noXmlNames(options))); + } + } + @Override public void addInterfaces(Map options, MessageDef def, List generalizations) { if (noXml(options)) { @@ -60,6 +102,21 @@ public FileGenerator messageInterfaceContents(Map options, Messa return new AbstractMessageGenerator(options) { @Override protected void generate() { + if (isOpenWorld(options) && def.isAbstract() && !def.hasExtends()) { + nl(); + line("/** Registry for dynamically registered subtypes by their XML element names. */"); + line("static final java.util.Map> " + XML_REGISTRY + " = new java.util.HashMap<>();"); + nl(); + line("/**"); + line(" * Registers a subtype factory for reading elements with the given name in XML format."); + line(" */"); + line("static void " + REGISTER_XML + "(String elementName, de.haumacher.msgbuf.data.Factory factory) {"); + { + line(XML_REGISTRY + ".put(elementName, factory);"); + } + line("}"); + } + nl(); line("/** Creates a new {@link " + typeName(def) + "} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */"); line("public static " + typeName(def) + " " + readerMethod(def) + "(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException {"); @@ -86,6 +143,9 @@ protected void generate() { line("public static final String " + xmlTypeNameConstant(def) + " = \"" + xmlTypeName(def) + "\";"); for (Field field : def.getFields()) { + if (!xmlSerialized(field)) { + continue; + } nl(); line("/** XML attribute or element name of a {@link #" + getterName(field) + "} property. */"); line("private static final String " + xmlFieldNameConstant(field) + " = \"" + xmlFieldName(field) + "\";"); @@ -123,8 +183,23 @@ protected void generate() { line("super.writeAttributes(out);"); } for (Field field : def.getFields()) { + if (!xmlSerialized(field)) { + continue; + } if (field.getType().kind() == Type.TypeKind.PRIMITIVE_TYPE || isEnum(field.getType())) { + // A missing value is omitted (a missing JSON value is written as JSON null). + boolean omitMissing = Util.isNullable(field) && !isJson(field); + // The default value of a bytes field is null, even if it is not nullable. + boolean omitNull = !Util.isNullable(field) && Util.isSingleBytes(field); + if (omitMissing) { + line("if (" + CodeConvention.hasName(field) + "()) {"); + } else if (omitNull) { + line("if (" + CodeConvention.getterName(field) + "() != null) {"); + } line("out.writeAttribute(" + xmlFieldNameConstant(field) + ", " + asString(field, CodeConvention.getterName(field) + "()") + ");"); + if (omitMissing || omitNull) { + line("}"); + } } } } @@ -143,6 +218,9 @@ protected void generate() { boolean hasElementFields = false; for (Field field : def.getFields()) { + if (!xmlSerialized(field)) { + continue; + } Type type = field.getType(); switch (type.kind()) { case PRIMITIVE_TYPE: { @@ -210,6 +288,19 @@ protected void generate() { line("default: {"); { + if (isOpenWorld(options)) { + // Types of other files are only known through the registry of the hierarchy root. + String root = qTypeName(openWorldRoot(def)); + line("de.haumacher.msgbuf.data.Factory factory = " + root + "." + XML_REGISTRY + ".get(in.getLocalName());"); + line(root + " instance = factory == null ? null : factory.create();"); + line("if (instance instanceof " + implName(def) + ") {"); + { + line(implName(def) + " result = (" + implName(def) + ") instance;"); + line("result.readContentXml(in);"); + line("return result;"); + } + line("}"); + } line("internalSkipUntilMatchingEndElement(in);"); line("return null;"); } @@ -268,6 +359,9 @@ protected void generate() { line("switch (name) {"); { for (Field field : def.getFields()) { + if (!xmlSerialized(field)) { + continue; + } if (field.getType().kind() == Type.TypeKind.PRIMITIVE_TYPE || isEnum(field.getType())) { line("case " + xmlFieldNameConstant(field) + ": {"); { @@ -306,6 +400,9 @@ protected void generate() { { Set names = new HashSet<>(); for (Field field : def.getFields()) { + if (!xmlSerialized(field)) { + continue; + } if (!names.add(xmlFieldName(field))) { System.err.println("ERROR: Ambiguous element name '" + xmlFieldName(field) + "' in type '" + def.getName() + "'."); continue; @@ -435,18 +532,56 @@ protected void generate() { private void readPrimitiveXmlElement(Field field) { line("case " + xmlFieldNameConstant(field) + ": {"); { - line(setterName(field) + "(" + fromString(field, "in.getElementText()") + ");"); + if (field.isRepeated()) { + // The list parser evaluates its input twice. + line("String text = in.getElementText();"); + line(setterName(field) + "(" + fromString(field, "text") + ");"); + } else { + line(setterName(field) + "(" + fromString(field, "in.getElementText()") + ");"); + } line("break;"); } line("}"); } String xmlTypeNameRef(MessageDef def) { - return implName(def) + "." + xmlTypeNameConstant(def); + String implRef = simpleNameInScopeOfGeneralizations(def) ? implName(def) : qImplName(def); + return implRef + "." + xmlTypeNameConstant(def); } }; } + /** + * Name of the registry of XML element names in the root interface of an + * option OpenWorld hierarchy. + */ + public static final String XML_REGISTRY = "XML_REGISTRY"; + + /** + * Name of the method in the root interface of an option OpenWorld hierarchy + * that registers a factory for an XML element name. + */ + public static final String REGISTER_XML = "registerXml"; + + /** + * Name of the constant with the XML element name of the given message in its implementation class. + */ + public static String xmlElementConstant(MessageDef def) { + return CodeUtil.allUpperCase(def.getName()) + "__XML_ELEMENT"; + } + + private static boolean isOpenWorld(Map options) { + return AbstractMessageGenerator.isTrue(options.get("OpenWorld"), false); + } + + private static MessageDef openWorldRoot(MessageDef def) { + MessageDef result = def; + while (result.getExtendedDef() != null) { + result = result.getExtendedDef(); + } + return result; + } + private boolean noXml(Map options) { return options.get("NoXml") != null; } @@ -460,6 +595,10 @@ String readerMethod(MessageDef def) { } String xmlTypeName(MessageDef def) { + return xmlTypeName(def, _noXmlNames); + } + + private static String xmlTypeName(MessageDef def, boolean noXmlNames) { Optional