diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 00000000..1f372d4e --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,21 @@ +{ + "permissions": { + "allow": [ + "Bash(mvn *)" + ], + "deny": [] + }, + "sandbox": { + "filesystem": { + "allowWrite": [ + "~/.m2/repository" + ] + }, + "network": { + "allowedHosts": [ + "repo.maven.apache.org", + "dev.top-logic.com" + ] + } + } +} 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/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 00000000..6d656553 --- /dev/null +++ b/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/=utf-8 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..c8aae8dd --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,132 @@ +# Changelog + +## 1.3.0 + +### New Features +- **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 +- **GWT compatibility for `json` field type**: Remove XML serialization (`javax.xml.stream.*`) from `JsonValue` envelope classes in `msgbuf-api`, which broke GWT compilation. JSON fields in XML format are serialized as JSON text strings instead. + +## 1.2.0 + +### New Features +- **`json` field type**: Native JSON value type for carrying opaque JSON data without double-serialization. In JSON format, values are written inline; for binary, a `JsonValue` envelope hierarchy is used. Java API uses `Object` (Map, List, String, Number, Boolean, null). +- **`option OpenWorld`**: Cross-file protocol extension for abstract type hierarchies. Subtypes can be defined in separate `.proto` files and modules using `import` and `extends`. Extension types are discovered at runtime via `ServiceLoader`. +- **Classpath-based import resolution**: Imports are resolved from compile-scope dependency JARs, so no file system paths to base modules are needed. +- **Cross-file message embedding**: Import mechanism supports using messages from one protocol as field types in another (not just `extends`). +- **`-resources` CLI argument**: Configure output directory for generated `META-INF/services` descriptors. +- **`-cp` CLI argument**: Specify JARs to search for imported `.proto` files. +- **Maven plugin `includePaths` parameter**: Configure additional include paths for proto file resolution. + +### Bug Fixes +- **Binary map serialization**: Fix missing write implementation for `map` fields in binary format. + +## 1.1.11 + +### New Features +- **`option UnorderedMaps`**: Use `HashMap` instead of `LinkedHashMap` for map properties when insertion order is not important. +- **`@Singular("item")` annotation**: Specify singular form for repeated fields, overriding automatic pluralization heuristics. +- **Default field values**: Fields can specify inline default values using `= value` syntax. +- **Backtick-quoted identifiers**: Use backticks to escape identifiers that clash with msgbuf keywords. +- **Primitive type aliases**: `int` for `int32`, `long` for `int64`, `boolean` for `bool`. +- **`@Operations("ClassName")` annotation**: Mix-in interfaces with operations on data classes. +- **Dart code generation**: `option DartLib` generates Dart data classes with JSON serialization. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..4600bed1 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,109 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +MsgBuf is a code generator for GWT-compatible Java data classes suitable for typed client-server messaging. It generates Java classes from `.proto` definition files with features beyond standard protobuf: inheritance, abstract classes, polymorphic data composition, and visitor pattern generation. + +Supports multiple serialization formats: JSON (primary), Binary, and XML. + +## Project Structure + +Multi-module Maven project. Build order matters — modules depend on each other sequentially: + +1. **de.haumacher.msgbuf** (`msgbuf-api`) — Runtime library with base classes, serialization support, GWT-compatible I/O abstractions. Apache-2.0. +2. **de.haumacher.msgbuf.generator** (`msgbuf-generator`) — Code generator using JavaCC parser. GPL-3.0-or-later. **Self-bootstrapping**: the generator's own AST (`generator/ast/proto.proto`) is defined in msgbuf syntax and generates the Java classes the generator uses internally. +3. **msgbuf-generator-maven-plugin** — Maven plugin wrapper for the generator. +4. **de.haumacher.msgbuf.eclipse** — Eclipse plugin (separate build, not in reactor). + +## Building and Testing + +```bash +# Full build (must be done in order: api → generator → plugin) +mvn clean install + +# Build individual module +mvn clean install -pl de.haumacher.msgbuf +mvn clean install -pl de.haumacher.msgbuf.generator + +# Run all tests +mvn test + +# Single module tests +mvn test -pl de.haumacher.msgbuf.generator + +# Single test class +mvn test -pl de.haumacher.msgbuf.generator -Dtest=test.hierarchy.TestHierarchy + +# Run generator standalone (after building) +java -jar de.haumacher.msgbuf.generator/target/msgbuf-generator-*-full.jar +``` + +## Generator Pipeline + +The code generation follows a 4-stage pipeline in `Generator.main()`: + +1. **Parsing** — JavaCC grammar (`protobuf.jj`) parses `.proto` files into AST nodes (`DefinitionFile` → `MessageDef`/`EnumDef` → `Field`) +2. **Specialization building** — Resolves type references, links inheritance hierarchies (`extends`), populates `specializations` lists for polymorphism +3. **ID synthesis** — `TypeIdSynthesizer` assigns type IDs for binary serialization; `FieldIDSynthesizer` auto-assigns field indices where not explicit +4. **Code generation** — `PackageGenerator` visitor dispatches to `MessageGenerator` (concrete classes), `EnumGenerator` (enums). Uses `GeneratorPlugin` SPI for extensibility. + +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/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 + +Core class hierarchy in `msgbuf-api`: + +- `DataObject` (interface) — `writeTo(JsonWriter)`, `writeContent()`, `readContent()` +- `AbstractDataObject` — Base impl with `writeFields()`/`readField()` hooks +- `ReflectiveDataObject` — Adds reflective property access (`get(field)`, `set(field, value)`) +- `Observable` — Change tracking with listener registration + +GWT compatibility: no `java.io.Reader/Writer` — uses custom `StringR`/`StringW` and reimplemented `JsonReader`/`JsonWriter` based on Gson. + +Generated classes have two property access patterns: +- **Public API**: `setField(value)` returns `this` for fluent chaining +- **Internal API**: `internalSetField(value)` triggers listeners, no chaining + +## Proto File Syntax + +Extensions beyond standard protobuf: +- `abstract message Foo { ... }` — Abstract base classes +- `message Bar extends Foo { ... }` — Inheritance +- `transient` fields — Not serialized +- Annotations: `@Name("x")`, `@Nullable`, `@Embedded`, `@Container`, `@Ref`, `@Reverse("prop")`, `@Operations("ClassName")`, `@Singular("item")` +- File-level options: `option NoInterfaces;`, `option NoBinary;`, `option NoJson;`, `option NoXml;`, `option NoReflection;`, `option NoListener;`, `option NoVisitor;`, `option SharedGraph;`, `option UnorderedMaps;` +- Backtick identifiers for reserved words: `` QName `package`; `` + +## Key Gotchas + +- **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**: 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. + +## Testing + +Test proto files and their tests are in `de.haumacher.msgbuf.generator/src/test/java/test/`: +- `test.hierarchy` — Polymorphism, visitor pattern +- `test.container` / `test.references` — Bidirectional references, containment +- `test.graph` — Shared graph synchronization +- `test.nullable`, `test.embedded`, `test.operations`, `test.defaultvalue`, `test.transientprops`, `test.onlyxml` +- Various option combinations (NoInterfaces, NoJson, etc.) + +Maven plugin integration tests: `msgbuf-generator-maven-plugin/src/it/` + +## Important Constraints + +- Java 11+ required (`maven.compiler.source/target = 11`) +- Generated code must be GWT-compatible (no `java.io` usage in `msgbuf-api`) +- 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 new file mode 100644 index 00000000..f804cc66 --- /dev/null +++ b/HOWTO-RELEASE.md @@ -0,0 +1,50 @@ +# How to release to Maven Central + +## Set stable version number and tag version + +``` +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 + +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. 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 492482d3..e4d575cb 100644 --- a/README.md +++ b/README.md @@ -6,19 +6,75 @@ Inspired by Google's [protocol buffers](https://developers.google.com/protocol-b In contrast to `protobuf`, `msgbuf` supports: * Code generation compatible with the [GWT Java-to-Javascript compiler](http://www.gwtproject.org/). * Inheritance of data classes. - * Abstract data classes defining the root of a hierarchy of exchangable data fragments. + * Abstract data classes defining the root of a hierarchy of exchangeable data fragments. * Polymorphic data compositions. - * [Visitor pattern](https://en.wikipedia.org/wiki/Visitor_pattern) for processing polomorphic data structures. + * [Visitor pattern](https://en.wikipedia.org/wiki/Visitor_pattern) for processing polymorphic data structures. -`msgbuf` currently serializes messages in JSON format. For GWT-compatibility it uses a modified `JsonReader`/`JsonWriter` from the [gson library](https://github.com/google/gson) that was abstracted from the unsupported `Reader`/`Writer` Java API. +`msgbuf` serializes messages in JSON, Binary, and XML formats. For GWT-compatibility it uses a modified `JsonReader`/`JsonWriter` from the [gson library](https://github.com/google/gson) that was abstracted from the unsupported `Reader`/`Writer` Java API. + +## Setup with Maven + +### Add the MsgBuf runtime library dependency to your project + +```xml + + de.haumacher.msgbuf + msgbuf-api + 1.3.0 + +``` + +### Add the MsgBuf generator to your pom.xml + +To the `build/plugins` section add: + +```xml + + de.haumacher.msgbuf + msgbuf-generator-maven-plugin + 1.3.0 + + + + generate-protocols + + generate + + + + +``` + +Now you are ready to create `*.proto` files in your source folder and build them with `mvn compile`. + +### Where to place proto files + +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`. Assume, you want to describe shapes in a graphics application, you could define the data types as follows. You may start with an `abstract` shape class, defining coordinates of the origin of its coordinate system: + +Add `src/main/java/my/app/model/shape.proto` with the following contents: ```protobuf -syntax = "msgbuf"; +package my.app.model; abstract message Shape { int32 xCoordinate; @@ -49,6 +105,551 @@ 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 +have explicit numeric IDs assigned: + +```protobuf +enum Corpus { + UNIVERSAL = 0; + WEB = 1; + IMAGES = 2; +} +``` + +Enums can also be nested inside messages: + +```protobuf +message SearchRequest { + enum Corpus { + UNIVERSAL = 0; + WEB = 1; + } + Corpus corpus; +} +``` + +### Nested messages + +Messages can be nested inside other messages: + +```protobuf +message SearchResponse { + message Result { + string url; + string title; + repeated string snippets; + } + repeated Result results; +} +``` + +### 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 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 { + string name; + transient string cachedValue; +} +``` + +### Backtick-quoted identifiers + +Backticks can be used to escape identifiers that clash with msgbuf keywords: + +```protobuf +message NullableValues { + @Nullable + int `int`; + @Nullable + boolean `boolean`; +} +``` + +### Primitive type aliases + +In addition to the protobuf type names, `msgbuf` supports shorter aliases: +- `int` for `int32` +- `long` for `int64` +- `boolean` for `bool` + +### Native JSON value type (`json`) + +The `json` type represents an opaque JSON value — any valid JSON structure (object, array, string, number, boolean, or null). This avoids double-serialization when a message needs to carry dynamically-typed data: + +```protobuf +message PatchEvent { + string controlId; + json patch; +} +``` + +In JSON format, the value is written natively without string-wrapping: + +```json +{"controlId":"c1","patch":{"nodes":{"n1":{"x":100}}}} +``` + +The generated Java API uses `Object` as the field type. Supported value types are `Map`, `List`, `String`, `Long`, `Double`, `Boolean`, and `null`: + +```java +Map patch = new LinkedHashMap<>(); +patch.put("nodes", ...); +PatchEvent event = PatchEvent.create() + .setControlId("c1") + .setPatch(patch); + +// Reading back: +Object value = event.getPatch(); // Map, List, String, Number, Boolean, or null +``` + +For binary serialization, json values are wrapped in a `JsonValue` message envelope (defined in `de.haumacher.msgbuf.json.value`). For XML, json values are encoded as JSON strings in element text. + +## Global protocol options + +### `option NoJson` +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 (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. + +### `option NoInterfaces` +Disables generation interfaces for data classes. Normally, data classes are represented by a Java interface. This +enables multiple inheritance for data classes. To reduce the amount of generated code, this can be disabled for simple +cases, where no multiple inheritance is required. + +### `option NoListener` +Disables generation of listener interfaces and corresponding registration methods. Add this options, if observing +data classes for changes is not required. + +### `option NoReflection` +Disables generation of reflective access methods that allow access to properties through their property names. + +### `option NoVisitor` +Disables generation of visitor interfaces and visit methods. + +### `option NoVisitorExceptions` +Produces visitor interfaces that cannot throw declared exceptions. + +### `option NoTypeKind` +Suppresses the type kind enumeration for a data class hierarchy. + +### `option SharedGraph` +Allows to handle multiple synchronized instances of a data class graph. Each graph can be observed for changes. Changes +generate synchronization messages to keep other instances of the same shared graph up to date. With this option, +a shared graph can be instantiated on a server, transferred to a client while keeping the state in sync when changes +occur on each side. + +### `option UnorderedMaps` +Uses `HashMap` instead of `LinkedHashMap` for map-type properties. By default, map properties use `LinkedHashMap` to +preserve insertion order. This option switches to `HashMap` for better performance when insertion order is not important. + +Example: +```protobuf +option UnorderedMaps; // Use HashMap for better performance + +message Config { + map settings; // Will use HashMap instead of LinkedHashMap +} +``` + +### `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`. + +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 +option OpenWorld; + +abstract message Event { + long timestamp; +} + +message TextEvent extends Event { + string text; +} +``` + +```protobuf +// extension-module: graph-events.proto +import "../base-module/events.proto"; + +message GraphPatchEvent extends base.pkg.Event { + string controlId; + string patch; +} +``` + +Extension types are discovered at runtime via `ServiceLoader`. The generator produces a registration class +(e.g. `GraphEventsTypes`) and a `META-INF/services` descriptor automatically when the `-resources` output +directory is configured. On platforms without `ServiceLoader` (e.g. GWT), call `GraphEventsTypes.init()` explicitly. + +The base module's `.proto` files should be packaged as resources in its JAR (e.g. in `src/main/resources`). +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` 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 + +``` + +Imports are resolved automatically from the compile classpath. If the base module packages its `.proto` files +as resources, no additional configuration is needed beyond declaring the dependency. + +CLI usage (standalone, without Maven): +``` +java -jar msgbuf-generator.jar -out src/main/java -resources src/main/resources -cp base-module.jar extension.proto +``` + +The `-cp` option specifies JARs to search for imported `.proto` files. The `-I` option can still be used +for file system include paths. + +## Message options + +### Mix-in interfaces (`@Operations(...)`) + +The data classes can extends mix-in interfaces with operations. + +```protobuf +/** The data class */ +@Operations("test.operations.DataOperations") +message Data { + int x; +} +``` +```java +/** The mix-in interface with operations on data. */ +public interface DataOperations { + /** Access to the data. */ + Data self(); + + /** Operation added to data class. */ + default void inc() { + self().setX(self().getX() + 1); + } +} + +/** Testing the mix-in operation. */ +public void testOperations() { + Data data = Data.create(); + data.inc(); + data.inc(); + assertEquals(2, data.getX()); +} +``` + +## Property options + +### `@Nullable` +A property of a primitive type that does not allow `null` values (e.g. `int` and `string`) can be explicitly marked to +allow `null` values. + +### `@Singular("item")` +Specifies the singular form for a repeated field, used when generating `addXxx()` and `removeXxx()` methods. This annotation +takes precedence over the automatic pluralization heuristics. Useful for irregular plurals or when the heuristics produce +incorrect results. + +Example: +```protobuf +message Container { + @Singular("person") + repeated string people; // Generates addPerson() instead of addPeople() + + @Singular("child") + repeated string children; // Generates addChild() instead of addChildren() + + @Singular("datum") + repeated string data; // Generates addDatum() instead of addData() +} +``` + +### `@Name("myProp")` +Sets a custom property name. This name is used in JSON serialization. + +### `@XmlName("myProp")` +Sets a custom tag name for XML serialization. + +### `@Reverse("otherProp")` +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. 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. + +### `@type_id(4711)` +Sets a custom type discriminator ID for binary serialization of polymorphic hierarchies. + +### Default values +Fields can specify default values inline using `= value` syntax: + +```protobuf +message Config { + string name = "default"; + int count = 42; + double ratio = 3.14; + bool enabled = true; +} +``` + +### `map` fields +Map-type fields are supported using the `map` syntax: + +```protobuf +message Config { + map settings; + map counts; +} +``` + +### XML reference embedding (`@Embedded`) +When serializing data classes to XML, all data fields and references are normally represented by XML tags with the same +name as the field or reference. By adding the `@Embedded` annotation to a reference, the tag for the reference can be +omitted. The contents of the reference is placed directly within the tag for the containing element. Care must be taken +that the tag names for referenced elements do not clash with tag names of other attributes and references of the +container. + +In the following example, a container with contents A and B can be written `` instead of +wrapping the contents into an extra element as in ``. + +```protobuf +message Container { + @Embedded + repeated Base contents; +} + +abstract message Base {} +message A extends Base {} +message B extends Base {} +``` + +However, even with the `@Embedded` annotation, the verbose serialization with the wrapping reference element is also +understood. + +## Plugin options + +### `option DartLib = "path/to/output.dart";` +Generates a Dart library file containing Dart data classes with JSON serialization support for all messages and enums +defined in the proto file. The path is relative to the generator output directory. + +```protobuf +option DartLib = "../lib/protocol.dart"; + +message MyMessage { + string name; + int count; +} +``` + +### TypeScript type definitions + +The generator can create a TypeScript module with type definitions for the JSON format of each `.proto` file. The +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 +data in the TypeScript application. + +TypeScript output is enabled in one of the following ways: + +* **Output directory for all files**: Set the Maven plugin parameter `typeScriptOutputDirectory` (user property + `typeScriptOutputDir`), or pass `-ts ` on the command line. A module is generated for each `.proto` file. + The module for a file `name.proto` with `package a.b.c;` is written to `a/b/c/name.ts` within that directory. +* **Per file**: `option TypeScript = "path/to/module.ts";` in a `.proto` file. The path is relative to the generator + output directory (like `option DartLib`) and takes precedence over the output directory. + +```xml + + de.haumacher.msgbuf + msgbuf-generator-maven-plugin + ... + + ${project.basedir}/src/main/ts/protocol + + ... + +``` + +Mapping of protocol definitions: + +| Protocol definition | TypeScript | +|---|---| +| `message M { ... }` | `export interface MJson { ... }` with the JSON property names of the fields (`@Name` is honored) | +| `message M extends B` | `export interface MJson extends BJson` | +| `abstract message A` | `export interface AJson`, plus `export type AnyAJson = ['TypeIdOfC1', C1Json] \| ...` if the hierarchy root is abstract (see below) | +| `enum E { ... }` | `export type EJson = 'A' \| 'B';` with the protocol names of the constants (`@Name` is honored) | +| `string` | `string` | +| `bytes` | `string \| null` (Base64 encoded, see below) | +| `bool` | `boolean` | +| `int32`, `int64`, `float`, `double`, ... | `number` | +| `json` | `unknown` | +| `repeated T` | `T[]` | +| `map` | `Record` | +| `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: + +* **Required and optional properties**: The types describe the JSON the Java side writes. A property is required + (`name: T`), if it is always written. Fields that are nullable (`@Nullable`, non-repeated references to messages, + `json`) are omitted from the JSON output when unset instead of being written as `null`, their properties are + optional (`name?: T`). A non-nullable `bytes` field has no value by default and is written as `null` then, it is + typed `string | null`. Note that the JSON reader is more lenient: it accepts any subset of properties and uses the + field's default value for a missing one. Explicit default values of fields are documented with a `@defaultValue` + tag. +* **Enum values**: An enum constant is written as its name exactly as spelled in the `.proto` file (e.g. `ICON_ONLY`), + unless a custom name is given with `@Name`: + + ```protobuf + enum DisplayMode { + @Name("icon-only") + ICON_ONLY; + @Name("label-only") + LABEL_ONLY; + } + ``` + + generates `export type DisplayModeJson = | 'icon-only' | 'label-only';`. +* **Polymorphism**: A value of an abstract message type in a hierarchy with an abstract root is written as a tuple + of its type ID and its properties, `["Circle", {"r": 5}]` (see [Polymorphic JSON serialization](#polymorphic-json-serialization)). + For each such abstract message `A`, a union type `AnyAJson` of the tuples of all known concrete specializations is + 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 + name in back ticks, and an unresolvable link becomes its label or the target in back ticks. The doc comment + (`/** ... */`) before the `syntax` or `package` declaration of a `.proto` file becomes the module's + `@packageDocumentation` comment. +* **Module paths**: Imports use relative module specifiers without file extension (e.g. `'../common/common'`), as + resolved by bundlers and `moduleResolution: "bundler"`. An imported `.proto` file is expected to have its module + 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, no helper functions are generated for them. A generated `AnyAJson` union type may clash with + a message named `AnyA`. + ## Installation in Eclipse There is an Eclipse plugin providing a project builder that automatically generates corresponding Java files whenever you create or modify a `*.proto` definition file. To install and enable the plugin with the following steps: @@ -65,17 +666,7 @@ There is an Eclipse plugin providing a project builder that automatically genera * Select your project in the `Package Explorer`. * In the context menu, select `Configure > Enable MsgBuf Builder`. -### Add project dependency to the MsgBuf runtime libary - -``` - - de.haumacher.msgbuf - msgbuf-api - 1.0.3 - -``` - -### Test the installtion +### Test the installation * Create a `MyMessage.proto` file in one of your packages in the source folder. * Add the package definition and a message declaration. @@ -99,13 +690,84 @@ public final void writeTo(JsonWriter out) throws IOException { } ``` +Note that `JsonReader` and `JsonWriter` use `de.haumacher.msgbuf.io.Reader` and `de.haumacher.msgbuf.io.Writer` instead of `java.io.Reader` and `java.io.Writer`. This is required for GWT compatibility, since `java.io` is not available in GWT. For in-memory string-based serialization, use `StringR` and `StringW`: + +```java +// Writing to a JSON string: +StringW out = new StringW(); +rectangle.writeTo(new JsonWriter(out)); +String json = out.toString(); + +// Reading from a JSON string: +Rectangle copy = Rectangle.readRectangle(new JsonReader(new StringR(json))); +``` + +On the server side (where GWT compatibility is not needed), you can use `ReaderAdapter` and `WriterAdapter` from `de.haumacher.msgbuf.server.io` to wrap standard `java.io.Reader`/`java.io.Writer` instances: + +```java +// Reading from a java.io.Reader: +Rectangle r = Rectangle.readRectangle(new JsonReader(new ReaderAdapter(javaIoReader))); + +// Writing to a java.io.Writer: +rectangle.writeTo(new JsonWriter(new WriterAdapter(javaIoWriter))); +``` + In polymorphic hierarchy of classes as defined above, it is not enough for a class to just write its own properties. Consider a `Group` instance from the example above. Its `shapes` list may contain multiple instances of either circles, rectangles, or even nested groups. Therefore, a class in a polymorphic hierarchy not only serializes its properties, but also its type. Reading back such polymorphic instance instantiates the correct class and fills it with its properties. ### Visitor pattern -For processing polymorphic messages, generated classes provide support for the [visitor pattern](https://en.wikipedia.org/wiki/Visitor_pattern) to allow writing custom code for each possible sub-type. Since the generated code should not be modified, you cannot add custom code directly to the data class. If you want to process (e.g. render) a received shape instance from the example above, you could of cause use an `instanceof` test to handle circles differently from rectangles and groups. But this leads to fragile code, where one of the possible choices is missed. +In a client-server messaging scenario, the server (or client) receives polymorphic messages and must dispatch each one to the appropriate handler. Consider a protocol with different request types: + +```protobuf +abstract message Request { + string sessionId; +} + +message LoginRequest extends Request { + string username; + string password; +} + +message QueryRequest extends Request { + string query; + int32 limit; +} + +message LogoutRequest extends Request { +} +``` + +You could use `instanceof` checks to handle each request type, but this is fragile — if a new request type is added to the protocol, the compiler won't warn you about the missing case, leading to silent failures at runtime. + +The generated visitor pattern solves this. Each abstract message hierarchy generates a `Visitor` interface with a case for every concrete subtype. When a new message type is added, every visitor implementation fails to compile until the new case is handled, guaranteeing completeness at compile time. + +```java +public class RequestHandler implements Request.Visitor { + @Override + public Response visit(LoginRequest self, Session session) { + return authenticate(self.getUsername(), self.getPassword()); + } + + @Override + public Response visit(QueryRequest self, Session session) { + return executeQuery(self.getQuery(), self.getLimit()); + } + + @Override + public Response visit(LogoutRequest self, Session session) { + session.invalidate(); + return Response.ok(); + } +} + +// Dispatching a received message: +Request request = Request.readRequest(new JsonReader(input)); +Response response = request.visit(handler, session); +``` + +The visitor pattern also works for non-messaging use cases. For the shape hierarchy defined above, a renderer could be implemented as follows. -A better alternative is the visitor pattern. This allows to separate processing code from the data class hierarchy without `instanceof` tests. An `abstract` base class provides a `Visitor` interface and a `visit(...)` method accepting such a visitor: +An `abstract` base class provides a `Visitor` interface and a `visit(...)` method accepting such a visitor: ```java public abstract class Shape { @@ -131,7 +793,7 @@ public abstract class Shape { } ``` -Each of the concrete sub-classes implement the `abstract` visit-method by delegating to the correspoinding case-method from the `Visitor` interface: +Each of the concrete sub-classes implement the `abstract` visit-method by delegating to the corresponding case-method from the `Visitor` interface: ```java public class Rectangle extends Shape { @@ -145,7 +807,7 @@ public class Rectangle extends Shape { } ``` -This allow to creating e.g. a renderer implementation that is able to process all concrete types from the shape hierarchy by applying the appropriate code to them: +This allows creating e.g. a renderer implementation that handles all concrete types from the shape hierarchy: ```java public class ShapeRenderer implements Shape.Visitor { diff --git a/de.haumacher.msgbuf.eclipse/.classpath b/de.haumacher.msgbuf.eclipse/.classpath index fec2eab5..1c9b40d9 100644 --- a/de.haumacher.msgbuf.eclipse/.classpath +++ b/de.haumacher.msgbuf.eclipse/.classpath @@ -1,6 +1,10 @@ - + + + + + diff --git a/de.haumacher.msgbuf.eclipse/.settings/org.eclipse.jdt.core.prefs b/de.haumacher.msgbuf.eclipse/.settings/org.eclipse.jdt.core.prefs index ec1937b3..cd8d089a 100644 --- a/de.haumacher.msgbuf.eclipse/.settings/org.eclipse.jdt.core.prefs +++ b/de.haumacher.msgbuf.eclipse/.settings/org.eclipse.jdt.core.prefs @@ -1,12 +1,15 @@ eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate +org.eclipse.jdt.core.compiler.codegen.targetPlatform=11 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.compliance=11 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning org.eclipse.jdt.core.compiler.release=disabled -org.eclipse.jdt.core.compiler.source=1.8 +org.eclipse.jdt.core.compiler.source=11 diff --git a/de.haumacher.msgbuf.eclipse/META-INF/MANIFEST.MF b/de.haumacher.msgbuf.eclipse/META-INF/MANIFEST.MF index 74c1ce96..0f72a004 100644 --- a/de.haumacher.msgbuf.eclipse/META-INF/MANIFEST.MF +++ b/de.haumacher.msgbuf.eclipse/META-INF/MANIFEST.MF @@ -2,10 +2,10 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: MsgBuf Project Nature Bundle-SymbolicName: de.haumacher.msgbuf.eclipse;singleton:=true -Bundle-Version: 1.0.3.qualifier +Bundle-Version: 1.1.0.qualifier Require-Bundle: org.eclipse.core.resources;bundle-version="3.13.700", org.eclipse.core.runtime, org.eclipse.ui, - de.haumacher.msgbuf.generator;bundle-version="1.0.2" -Bundle-RequiredExecutionEnvironment: JavaSE-1.8 + de.haumacher.msgbuf.generator;bundle-version="1.1.0" +Bundle-RequiredExecutionEnvironment: JavaSE-11 Bundle-Vendor: haumacher.de diff --git a/de.haumacher.msgbuf.feature/feature.xml b/de.haumacher.msgbuf.feature/feature.xml index 6ac49396..be104c3b 100644 --- a/de.haumacher.msgbuf.feature/feature.xml +++ b/de.haumacher.msgbuf.feature/feature.xml @@ -2,7 +2,7 @@ diff --git a/de.haumacher.msgbuf.generator/.classpath b/de.haumacher.msgbuf.generator/.classpath index dc135e9b..cfb853a5 100644 --- a/de.haumacher.msgbuf.generator/.classpath +++ b/de.haumacher.msgbuf.generator/.classpath @@ -1,6 +1,6 @@ - + @@ -13,7 +13,7 @@ - + @@ -29,5 +29,12 @@ + + + + + + + diff --git a/de.haumacher.msgbuf.generator/.settings/org.eclipse.core.resources.prefs b/de.haumacher.msgbuf.generator/.settings/org.eclipse.core.resources.prefs index 5b781ec6..226a7eb3 100644 --- a/de.haumacher.msgbuf.generator/.settings/org.eclipse.core.resources.prefs +++ b/de.haumacher.msgbuf.generator/.settings/org.eclipse.core.resources.prefs @@ -1,3 +1,5 @@ eclipse.preferences.version=1 -encoding//src/main/java=UTF-8 -encoding//src/test/java=UTF-8 +encoding//src/main/java=utf-8 +encoding//src/test/java=utf-8 +encoding//src/test/resources=utf-8 +encoding/=utf-8 diff --git a/de.haumacher.msgbuf.generator/.settings/org.eclipse.jdt.core.prefs b/de.haumacher.msgbuf.generator/.settings/org.eclipse.jdt.core.prefs index 3a0745fd..2bd4e773 100644 --- a/de.haumacher.msgbuf.generator/.settings/org.eclipse.jdt.core.prefs +++ b/de.haumacher.msgbuf.generator/.settings/org.eclipse.jdt.core.prefs @@ -1,9 +1,9 @@ eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=11 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.compliance=11 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate @@ -13,4 +13,4 @@ org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning org.eclipse.jdt.core.compiler.release=disabled -org.eclipse.jdt.core.compiler.source=1.8 +org.eclipse.jdt.core.compiler.source=11 diff --git a/de.haumacher.msgbuf.generator/META-INF/MANIFEST.MF b/de.haumacher.msgbuf.generator/META-INF/MANIFEST.MF index 19ca3122..9e60e807 100644 --- a/de.haumacher.msgbuf.generator/META-INF/MANIFEST.MF +++ b/de.haumacher.msgbuf.generator/META-INF/MANIFEST.MF @@ -2,10 +2,10 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: MsgBuf Code Generator Bundle-SymbolicName: de.haumacher.msgbuf.generator -Bundle-Version: 1.0.2.qualifier +Bundle-Version: 1.1.0.qualifier Export-Package: de.haumacher.msgbuf.generator, de.haumacher.msgbuf.generator.ast, de.haumacher.msgbuf.generator.parser -Require-Bundle: de.haumacher.msgbuf;bundle-version="1.0.0" -Bundle-RequiredExecutionEnvironment: JavaSE-1.8 +Require-Bundle: de.haumacher.msgbuf;bundle-version="1.1.0" +Bundle-RequiredExecutionEnvironment: JavaSE-11 Bundle-Vendor: haumacher.de diff --git a/de.haumacher.msgbuf.generator/bin/Generate MsgBuf.launch b/de.haumacher.msgbuf.generator/bin/Generate MsgBuf.launch index c9b395e0..32ea7641 100644 --- a/de.haumacher.msgbuf.generator/bin/Generate MsgBuf.launch +++ b/de.haumacher.msgbuf.generator/bin/Generate MsgBuf.launch @@ -1,13 +1,16 @@ + + + diff --git a/de.haumacher.msgbuf.generator/pom.xml b/de.haumacher.msgbuf.generator/pom.xml index 629f3a7b..3f38245b 100644 --- a/de.haumacher.msgbuf.generator/pom.xml +++ b/de.haumacher.msgbuf.generator/pom.xml @@ -3,8 +3,8 @@ de.haumacher.msgbuf - 1.0.4-SNAPSHOT msgbuf-parent + 1.3.1-SNAPSHOT msgbuf-generator @@ -34,26 +34,47 @@ de.haumacher.msgbuf msgbuf-api - 1.0.4-SNAPSHOT + 1.3.1-SNAPSHOT junit junit - 3.8.2 + 4.13.2 test + + + ${project.build.sourceDirectory} + + **/*.java + + + maven-compiler-plugin 3.8.1 - - 1.8 - 1.8 - + + + + org.codehaus.mojo + javacc-maven-plugin + 3.1.1 + + + + javacc + + + ${project.basedir}/src/main/java + ${project.basedir}/src/main/java + + + @@ -78,5 +99,40 @@ + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.codehaus.mojo + + + javacc-maven-plugin + + + [3.1.1,) + + + javacc + + + + + + + + + + + + \ No newline at end of file diff --git a/de.haumacher.msgbuf.generator/src/main/java/META-INF/services/de.haumacher.msgbuf.generator.GeneratorPlugin b/de.haumacher.msgbuf.generator/src/main/java/META-INF/services/de.haumacher.msgbuf.generator.GeneratorPlugin new file mode 100644 index 00000000..020ede1a --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/main/java/META-INF/services/de.haumacher.msgbuf.generator.GeneratorPlugin @@ -0,0 +1 @@ +de.haumacher.msgbuf.generator.plugins.XmlStreamingPlugin \ No newline at end of file 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 a3a20a98..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 @@ -8,6 +8,10 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; + +import de.haumacher.msgbuf.generator.ast.DefinitionFile; +import de.haumacher.msgbuf.generator.common.Util; import de.haumacher.msgbuf.generator.ast.Flag; import de.haumacher.msgbuf.generator.ast.MessageDef; @@ -23,12 +27,22 @@ public abstract class AbstractMessageGenerator extends AbstractJavaGenerator { protected final boolean _noInterfaces; + protected final String _packageSuffix; + /** * Creates a {@link AbstractMessageGenerator}. */ - public AbstractMessageGenerator(Map options) { + public AbstractMessageGenerator(Map options, String packageSuffix) { _options = options; _noInterfaces = isTrue(options.get("NoInterfaces"), false); + _packageSuffix = packageSuffix; + } + + /** + * Creates a {@link AbstractMessageGenerator} that does not create top-level file contents. + */ + protected AbstractMessageGenerator(Map options) { + this(options, null); } public Map getOptions() { @@ -51,24 +65,38 @@ protected String qImplName(MessageDef def) { if (_noInterfaces) { return qTypeName(def); } else { - return CodeConvention.qImplName(def); + return CodeConvention.qImplName(CodeConvention.IMPL_PACKAGE_SUFFIX, def); } } protected static List concreteSpecializations(MessageDef def) { ArrayList result = new ArrayList<>(); - addConcreteSpecializations(result, def); + addConcreteSpecializations(result, def, Util.definingFile(def)); return result; } - private static void addConcreteSpecializations(ArrayList result, MessageDef def) { - for (MessageDef specialization : def.getSpecializations()) { - if (!specialization.isAbstract()) { - result.add(specialization); - } - - addConcreteSpecializations(result, specialization); + private static void addConcreteSpecializations(ArrayList result, MessageDef def, DefinitionFile originFile) { + if (!def.isAbstract()) { + result.add(def); + } + + for (MessageDef specialization : localSpecializations(def, originFile)) { + addConcreteSpecializations(result, specialization, originFile); + } + } + + /** + * Returns the direct specializations of the given type. For OpenWorld protocols, + * only specializations from the same proto file as {@code originFile} are included. + * Cross-file extensions are discovered at runtime via the dynamic registry. + */ + protected static List localSpecializations(MessageDef def, DefinitionFile originFile) { + if (!Util.getFlag(originFile, "OpenWorld")) { + return def.getSpecializations(); } + return def.getSpecializations().stream() + .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 def6867d..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 @@ -9,6 +9,8 @@ import java.util.function.Function; import java.util.stream.Collectors; +import java.util.Optional; + import de.haumacher.msgbuf.generator.ast.Constant; import de.haumacher.msgbuf.generator.ast.CustomType; import de.haumacher.msgbuf.generator.ast.Definition; @@ -16,8 +18,10 @@ import de.haumacher.msgbuf.generator.ast.Field; import de.haumacher.msgbuf.generator.ast.MapType; import de.haumacher.msgbuf.generator.ast.MessageDef; +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.Util; import de.haumacher.msgbuf.generator.util.CodeUtil; @@ -39,22 +43,22 @@ public static String qTypeName(CustomType def) { } public static String qTypeName(Definition def) { - return qName(def, CodeConvention::typeName); + return qName(null, def, CodeConvention::typeName); } - public static String qImplName(Definition def) { - return qName(def, CodeConvention::implName); + public static String qImplName(String packageSuffix, Definition def) { + return qName(packageSuffix, def, CodeConvention::implName); } - public static String qName(Definition def, Function localNameConvention) { + public static String qName(String packageSuffix, Definition def, Function localNameConvention) { String scope; DefinitionFile file = def.getFile(); if (file == null) { - scope = qName(def.getOuter(), localNameConvention) + "."; + scope = qName(packageSuffix, def.getOuter(), localNameConvention) + "."; } else { QName pkg = file.getPackage(); - scope = pkg.getNames().size() == 0 ? "" : qName(pkg) + "."; + scope = pkg.getNames().size() == 0 ? (packageSuffix == null ? "" : packageSuffix + ".") : qName(pkg) + "." + (packageSuffix == null ? "" : packageSuffix + "."); } return scope + localNameConvention.apply(def.getName()); @@ -76,11 +80,7 @@ public static String qName(QName qName, Function localNameConven result.append('.'); } String part = names.get(n); - if (n < cnt - 1) { - result.append(part); - } else { - result.append(localNameConvention.apply(part)); - } + result.append(localNameConvention.apply(part)); } return result.toString(); } @@ -110,7 +110,7 @@ public static String binaryConstant(Field field) { } public static String constant(Field field) { - return allUpperCase(field.getName()); + return allUpperCase(field.getName()) + "__PROP"; } /** @@ -156,20 +156,83 @@ public static String removerName(Field field) { } private static String singularSuffix(Field field) { + // Check for explicit @Singular annotation first + OptionalBernhard Haumacher */ final class DefaultValueGenerator implements Type.Visitor { - - public static String mkDefaultValue(Field field) { + + private final Map _options; + + /** + * Creates a {@link DefaultValueGenerator}. + * + * @param options The global protocol options. + */ + public DefaultValueGenerator(Map options) { + _options = options; + } + + public String mkDefaultValue(Field field) { + String defaultValue = field.getDefaultValue(); + if (defaultValue != null) { + return defaultValue; + } + boolean nullable = Util.isNullable(field); if (nullable) { return "null"; } - + return mkDefaultValueNonNullable(field); } - public static String mkDefaultValueNonNullable(Field field) { + public String mkDefaultValueNonNullable(Field field) { if (field.isRepeated()) { return "new java.util.ArrayList<>()"; } else { @@ -38,17 +57,16 @@ public static String mkDefaultValueNonNullable(Field field) { } } - public static String mkDefaultValue(Type type) { - return type.visit(INSTANCE, null); + public String mkDefaultValue(Type type) { + return type.visit(this, null); } - private static final Type.Visitor INSTANCE = new DefaultValueGenerator(); - @Override public String visit(PrimitiveType self, Void arg) { switch (self.getKind()) { case BOOL: return "false"; case BYTES: return "null"; + case JSON: return "null"; case DOUBLE: return "0.0d"; case FLOAT: return "0.0f"; case STRING: return "\"\""; @@ -80,6 +98,13 @@ public String visit(CustomType self, Void arg) { @Override public String visit(MapType self, Void arg) { - return "new java.util.HashMap<>()"; + // Use LinkedHashMap by default to preserve insertion order + // Use HashMap only if UnorderedMaps option is explicitly set for performance reasons + boolean useUnorderedMaps = _options != null && AbstractMessageGenerator.isTrue(_options.get("UnorderedMaps"), false); + if (useUnorderedMaps) { + return "new java.util.HashMap<>()"; + } else { + return "new java.util.LinkedHashMap<>()"; + } } } \ No newline at end of file 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 08f9c5eb..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 @@ -63,10 +74,10 @@ protected void generate() { line("/**"); line(" * The protocol name of a {@link " + typeName(_def) + "} constant."); line(" *"); - line(" * @see #valueOfProtocol(String)"); + line(" * @see #" + CodeConvention.ENUM_VALUE_OF_PROTOCOL + "(String)"); line(" */"); line("@Override"); - line("public String protocolName() {"); + line("public String " + CodeConvention.ENUM_PROTOCOL_NAME_FUN + "() {"); { line("return _protocolName;"); } @@ -74,7 +85,7 @@ protected void generate() { nl(); line("/** Looks up a {@link " + typeName(_def) + "} constant by it's protocol name. */"); - line("public static " + typeName(_def) + " valueOfProtocol(String protocolName) {"); + line("public static " + typeName(_def) + " " + CodeConvention.ENUM_VALUE_OF_PROTOCOL + "(String protocolName) {"); List constants = _def.getConstants(); { line("if (protocolName == null) { return null; }"); @@ -87,11 +98,22 @@ 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 {"); { - line("out.value(protocolName());"); + line("out.value(" + CodeConvention.ENUM_PROTOCOL_NAME_FUN + "());"); } line("}"); @@ -99,10 +121,13 @@ protected void generate() { line("/** Reads a new instance from the given reader. */"); line("public static " + typeName(_def) + " " + CodeConvention.readerName(_def) + "(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException {"); { - line("return valueOfProtocol(in.nextString());"); + 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/FieldOperations.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/FieldOperations.java index 75d5de0e..9dcc2962 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/FieldOperations.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/FieldOperations.java @@ -3,8 +3,14 @@ */ package de.haumacher.msgbuf.generator; +import de.haumacher.msgbuf.generator.ast.CustomType; +import de.haumacher.msgbuf.generator.ast.Definition; import de.haumacher.msgbuf.generator.ast.Field; +import de.haumacher.msgbuf.generator.ast.MapType; +import de.haumacher.msgbuf.generator.ast.MessageDef; import de.haumacher.msgbuf.generator.ast.Option; +import de.haumacher.msgbuf.generator.ast.StringOption; +import de.haumacher.msgbuf.generator.ast.Type; /** * Mix-in interface for {@link Field} providing operations. @@ -13,15 +19,87 @@ */ public interface FieldOperations { - /** - * Annotations to this definition. + /** + * The implementation. */ - java.util.Map getOptions(); - + Field self(); /** Whether this field cannot be set by the application */ default boolean isDerived() { - return getOptions().get("Reverse") != null || getOptions().get("Container") != null; + return isReverse() || isContainer(); + } + + /** + * Whether this is a derived reference pointing to the owner of the object this referenec belongs to. + */ + default boolean isContainer() { + return self().getOptions().get("Container") != null; + } + + /** + * Whether this is a cross reference (not a composition which is the default). + */ + default boolean isRef() { + return self().getOptions().get("Ref") != null; } + /** + * Whether this is a reverse reference. + */ + default boolean isReverse() { + return getReverseAnnotation() != null; + } + + /** + * Whether this field is the reverse to the reference with the given name. + */ + default boolean isReverseOf(String name) { + return name.equals(getReverse()); + } + + /** + * The name of the inverse reference of this one. + * + * @return The name of the reverse reference to this one, or null if no such + * reference exists. + */ + default String getReverse() { + StringOption reverseOption = (StringOption) getReverseAnnotation(); + if (reverseOption == null) { + return null; + } + return reverseOption.getValue(); + } + + + /** + * The annotation marking this reference as "reverse". + */ + default Option getReverseAnnotation() { + return self().getOptions().get("Reverse"); + } + + /** + * The {@link Field} in this field's type that is marked as {@link #isContainer() container}, or + * null if no such field exists. + */ + default Field container() { + if (!isDerived() && !isRef()) { + Type contentType = self().getType(); + if (contentType instanceof MapType) { + contentType = ((MapType) contentType).getValueType(); + } + if (contentType instanceof CustomType) { + Definition contentDef = ((CustomType) contentType).getDefinition(); + if (contentDef instanceof MessageDef) { + // Field is a composition reference. + return ((MessageDef) contentDef).container(); + } + } + } + return null; + } + + + } 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 39b6195f..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 @@ -11,9 +11,16 @@ import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; +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; import java.util.Map; +import java.util.ServiceLoader; +import java.util.Set; import de.haumacher.msgbuf.generator.ast.CustomType; import de.haumacher.msgbuf.generator.ast.Definition; @@ -21,18 +28,24 @@ 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; 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; /** @@ -40,23 +53,111 @@ */ public class Generator { + /** + * Argument giving the output directory. + */ + public static final String OUTPUT_DIR_ARG = "-out"; + + /** + * Argument giving the resource output directory for generated service descriptors. + */ + public static final String RESOURCE_DIR_ARG = "-resources"; + + /** + * Argument giving the output directory for TypeScript type definitions. + * + *

+ * If given, a TypeScript module is generated for each .proto file, see + * {@link #setTypeScriptOut(File)}. + *

+ */ + public static final String TYPESCRIPT_DIR_ARG = "-ts"; + + /** + * File option giving the location of the TypeScript module to generate for a + * .proto file (relative to the output directory). + */ + public static final String TYPESCRIPT_OPTION = "TypeScript"; + + /** + * File extension of generated TypeScript modules. + */ + private static final String TS_EXTENSION = ".ts"; + + /** + * Module name for a .proto file whose file name is unknown. + */ + private static final String DEFAULT_MODULE_NAME = "index"; + private NameTable _table = new NameTable(); private File _out = new File("."); + private File _resourceOut; + private File _tsOut; + private Map _sourceNames = new HashMap<>(); private List _files = new ArrayList<>(); - + 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) { _out = out; } + public void setResourceOut(File resourceOut) { + _resourceOut = resourceOut; + } + + /** + * Sets the root directory for TypeScript type definitions. + * + *

+ * If set, a TypeScript module with type definitions for the JSON format is generated for each + * .proto file. The module for a file name.proto with + * package a.b.c; is written to a/b/c/name.ts within the given + * directory. + *

+ */ + public void setTypeScriptOut(File tsOut) { + _tsOut = tsOut; + } + + public void addIncludePath(File path) { + _includePaths.add(path); + } + + /** + * Sets a class loader used to resolve imports from the classpath. + * Proto files packaged as resources in dependency JARs can be found this way. + */ + public void setImportClassLoader(ClassLoader classLoader) { + _importClassLoader = classLoader; + } + public DefinitionFile load(String fileName) throws IOException, ParseException { return load(new File(fileName)); } public DefinitionFile load(File file) throws ParseException, IOException, FileNotFoundException { + 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)) { - return load(in); + content = load(parse(in)); } + _fileByPath.put(canonical, content); + _sourceNames.put(content, file.getName()); + resolveImports(content, file); + return content; } public DefinitionFile load(InputStream in) throws ParseException { @@ -85,32 +186,947 @@ public void generate(GeneratorPlugin plugin) { for (DefinitionFile file : _files) { 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, errors); + } + + // Propagate NoBinary and NoTypeKind to extension files that extend OpenWorld bases + for (DefinitionFile file : _files) { + 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) { - typeIdSynthesizer.process(file); + if (!Util.getFlag(file, "OpenWorld")) { + typeIdSynthesizer.process(file); + } } - + FieldIDSynthesizer synthesizer = new FieldIDSynthesizer(); for (DefinitionFile file : _files) { 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 + } + + plugin.init(file.getOptions()); + File dir = mkdir(file.getPackage()); - + PackageGenerator packageGenerator = new PackageGenerator(dir, file.getOptions(), plugin); for (Definition def : file.getDefinitions()) { def.visit(packageGenerator, null); } - + Option dartLib = file.getOptions().get("DartLib"); if (dartLib != null) { new DartLibGenerator(new File(_out, ((StringOption) dartLib).getValue()), file).run(); } + + if (generatesTypeScript(file)) { + File tsFile = typeScriptModule(file); + new TypeScriptGenerator(tsFile, file, sourceDescription(file), + other -> moduleSpecifier(tsFile, typeScriptModule(other)), _table).run(); + } + } + + // Generate registration classes and service loader descriptors for extension modules + List registrationClasses = new ArrayList<>(); + for (DefinitionFile file : _files) { + if (_importedFiles.contains(file)) { + continue; + } + List crossFileExtensions = findCrossFileExtensions(file); + if (!crossFileExtensions.isEmpty()) { + String fqClassName = generateRegistrationClass(file, crossFileExtensions, plugin); + registrationClasses.add(fqClassName); + } + } + if (!registrationClasses.isEmpty() && _resourceOut != null) { + generateServiceDescriptor(registrationClasses); + } + } + + /** + * 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. + * + *

+ * An explicit {@link #TYPESCRIPT_OPTION} is resolved against the output directory. Otherwise, + * the module is placed in the directory of the file's package (within the TypeScript output + * directory, or the output directory, if none is set) and named after the .proto + * file. + *

+ */ + private File typeScriptModule(DefinitionFile file) { + Option explicit = file.getOptions().get(TYPESCRIPT_OPTION); + if (explicit != null) { + return new File(_out, ((StringOption) explicit).getValue()).toPath().normalize().toFile(); + } + File result = _tsOut != null ? _tsOut : _out; + if (file.getPackage() != null) { + for (String name : file.getPackage().getNames()) { + result = new File(result, name); + } + } + return new File(result, moduleName(file) + TS_EXTENSION); + } + + private String moduleName(DefinitionFile file) { + String sourceName = _sourceNames.get(file); + if (sourceName == null) { + return DEFAULT_MODULE_NAME; + } + int dot = sourceName.lastIndexOf('.'); + return dot > 0 ? sourceName.substring(0, dot) : sourceName; + } + + private String sourceDescription(DefinitionFile file) { + String sourceName = _sourceNames.get(file); + if (file.getPackage() == null) { + return sourceName == null ? "" : sourceName; + } + String packagePath = String.join("/", file.getPackage().getNames()); + return sourceName == null ? packagePath : packagePath + "/" + sourceName; + } + + /** + * The relative module specifier (without file extension) to reference the given target module + * from the given module. + */ + private static String moduleSpecifier(File from, File to) { + java.nio.file.Path fromDir = from.getAbsoluteFile().toPath().normalize().getParent(); + java.nio.file.Path target = to.getAbsoluteFile().toPath().normalize(); + String relative = fromDir.relativize(target).toString().replace(File.separatorChar, '/'); + if (relative.endsWith(TS_EXTENSION)) { + relative = relative.substring(0, relative.length() - TS_EXTENSION.length()); + } + return relative.startsWith("../") ? relative : "./" + relative; + } + + private void validateOpenWorld(DefinitionFile file, List errors) { + boolean openWorld = Util.getFlag(file, "OpenWorld"); + if (!openWorld) { + return; + } + // OpenWorld implies NoBinary + file.getOptions().put("NoBinary", Flag.create().setValue(true)); + + 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."); + } } } + + private void propagateOpenWorldOptions(DefinitionFile file) { + if (Util.getFlag(file, "OpenWorld")) { + // Already an OpenWorld file, options already set + return; + } + 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) { + 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 + File resolved = resolveImportPathFromFileSystem(importPath, sourceFile); + if (resolved != null) { + String canonical = resolved.getCanonicalPath(); + if (_loadedFiles.contains(canonical)) { + addImport(file, _fileByPath.get(canonical)); + continue; + } + _loadedFiles.add(canonical); + DefinitionFile imported; + 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); + _importedFiles.add(imported); + resolveImports(imported, resolved); + continue; + } + + // Fall back to classpath + if (_importClassLoader != null) { + String resourceKey = "classpath:" + importPath; + if (_loadedFiles.contains(resourceKey)) { + addImport(file, _fileByPath.get(resourceKey)); + continue; + } + InputStream classpathStream = _importClassLoader.getResourceAsStream(importPath); + if (classpathStream != null) { + _loadedFiles.add(resourceKey); + DefinitionFile imported; + 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); + _importedFiles.add(imported); + // Recursive imports from classpath-loaded files can only resolve via classpath + resolveImportsFromClasspath(imported); + continue; + } + } + + error("Cannot resolve import '" + importPath + "' from '" + sourceFile + "'."); + } + } + + 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; + } + + if (_importClassLoader != null) { + InputStream classpathStream = _importClassLoader.getResourceAsStream(importPath); + if (classpathStream != null) { + _loadedFiles.add(resourceKey); + DefinitionFile imported; + 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); + _importedFiles.add(imported); + resolveImportsFromClasspath(imported); + continue; + } + } + + error("Cannot resolve import '" + importPath + "'."); + } + } + + private File resolveImportPathFromFileSystem(String importPath, File sourceFile) { + if (sourceFile != null) { + // 1. Relative to importing file's directory + File relative = new File(sourceFile.getParentFile(), importPath); + if (relative.isFile()) { + return relative; + } + } + // 2. From configured include paths + for (File includePath : _includePaths) { + File candidate = new File(includePath, importPath); + if (candidate.isFile()) { + return candidate; + } + } + return null; + } + private void buildSpecializations(DefinitionFile file) { NameTable table = _table; @@ -170,6 +1186,145 @@ public Void visit(EnumDef def, Void arg) { } } + private List findCrossFileExtensions(DefinitionFile file) { + List result = new ArrayList<>(); + for (Definition def : file.getDefinitions()) { + if (def instanceof MessageDef) { + collectCrossFileExtensions((MessageDef) def, file, result); + } + } + 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) { + if (!def.isAbstract() && hasOpenWorldGeneralizationInOtherFile(def, file)) { + result.add(def); + } + for (Definition inner : def.getDefinitions()) { + if (inner instanceof MessageDef) { + collectCrossFileExtensions((MessageDef) inner, file, result); + } + } + } + + 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]; + String className = Character.toUpperCase(baseName.charAt(0)) + baseName.substring(1) + "Types"; + + 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 + "'."); + w.println("package " + packageName + ";"); + w.println(); + w.println("/**"); + w.println(" * Registration of extension types for the OpenWorld protocol."); + w.println(" */"); + w.println("public class " + className + " implements de.haumacher.msgbuf.data.TypeRegistration {"); + w.println(); + w.println("\t@Override"); + w.println("\tpublic void register() {"); + for (MessageDef ext : extensions) { + 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(); + w.println("\t/**"); + w.println("\t * Explicit initialization for GWT or manual use."); + w.println("\t */"); + w.println("\tpublic static void init() {"); + w.println("\t\tnew " + className + "().register();"); + w.println("\t}"); + w.println("}"); + } + } catch (IOException ex) { + error("Error writing file '" + out + "'.", ex); + } + return packageName + "." + className; + } + + private void generateServiceDescriptor(List registrationClasses) { + File servicesDir = new File(_resourceOut, "META-INF/services"); + servicesDir.mkdirs(); + File descriptor = new File(servicesDir, "de.haumacher.msgbuf.data.TypeRegistration"); + + // Read existing entries to avoid duplicates (supports multiple generator runs) + Set existing = new HashSet<>(); + if (descriptor.isFile()) { + try (java.io.BufferedReader r = new java.io.BufferedReader(new java.io.InputStreamReader(new FileInputStream(descriptor), "utf-8"))) { + String line; + while ((line = r.readLine()) != null) { + line = line.trim(); + if (!line.isEmpty()) { + existing.add(line); + } + } + } catch (IOException ex) { + // Ignore, will overwrite + } + } + existing.addAll(registrationClasses); + + try (FileOutputStream os = new FileOutputStream(descriptor)) { + try (PrintWriter w = new PrintWriter(new OutputStreamWriter(os, "utf-8"))) { + System.out.println("Generating '" + descriptor + "'."); + for (String className : existing) { + w.println(className); + } + } + } catch (IOException ex) { + error("Error writing file '" + descriptor + "'.", ex); + } + } + class PackageGenerator implements Definition.Visitor { private final File _dir; private final Map _options; @@ -183,20 +1338,30 @@ public PackageGenerator(File dir, Map options, GeneratorPlugin p @Override public Void visit(EnumDef def, Void arg) { - return generateJava(CodeConvention.typeName(def), new EnumGenerator(def)); + return generateJava(CodeConvention.typeName(def), null, new EnumGenerator(_options, def)); } @Override public Void visit(MessageDef def, Void arg) { boolean noInterfaces = MessageGenerator.isTrue(_options.get("NoInterfaces"), false); if (!noInterfaces) { - generateJava(CodeConvention.typeName(def), new MessageGenerator(_table, _options, true, def, _plugin)); + generateJava(CodeConvention.typeName(def), null, new MessageGenerator(_table, _options, true, null, def, _plugin)); } - return generateJava(noInterfaces ? CodeConvention.typeName(def) : CodeConvention.implName(def), new MessageGenerator(_table, _options, false, def, _plugin)); + String packageSuffix = noInterfaces ? null : CodeConvention.IMPL_PACKAGE_SUFFIX; + return generateJava(noInterfaces ? CodeConvention.typeName(def) : CodeConvention.implName(def), packageSuffix, new MessageGenerator(_table, _options, false, packageSuffix, def, _plugin)); } - private Void generateJava(String name, FileGenerator generator) { - File out = new File(_dir, name + ".java"); + private Void generateJava(String name, String packageSuffix, FileGenerator generator) { + File dir = _dir; + if (packageSuffix != null) { + // Delete legacy file. + File old = new File(_dir, name + ".java"); + old.delete(); + + dir = new File(dir, packageSuffix); + } + dir.mkdirs(); + File out = new File(dir, name + ".java"); try (FileOutputStream os = new FileOutputStream(out)) { try (PrintWriter w = new PrintWriter(new OutputStreamWriter(os, "utf-8"))) { System.out.println("Generating '" + out + "'."); @@ -232,24 +1397,37 @@ protected void error(String message, IOException ex) { } } - public static void main(String[] args) throws ParseException, IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { + /** + * Main entry point invoked from the command line. + */ + public static void main(String... args) throws ParseException, IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { if (args.length == 0) { printHelp(); return; } File out = null; - GeneratorPlugin plugin = GeneratorPlugin.none(); Generator generator = new Generator(); for (int n = 0, cnt = args.length; n < cnt; ) { String arg = args[n++]; - if (arg.equals("-out")) { + if (arg.equals(OUTPUT_DIR_ARG)) { out = new File(args[n++]); + } else if (arg.equals(RESOURCE_DIR_ARG)) { + generator.setResourceOut(new File(args[n++])); + } else if (arg.equals(TYPESCRIPT_DIR_ARG)) { + generator.setTypeScriptOut(new File(args[n++])); } else if (arg.equals("-h")) { printHelp(); return; - } else if (arg.equals("-p")) { - plugin = plugin.andThen((GeneratorPlugin) Class.forName(args[n++]).newInstance()); - return; + } else if (arg.equals("-I")) { + generator.addIncludePath(new File(args[n++])); + } else if (arg.equals("-cp")) { + String classpath = args[n++]; + String[] entries = classpath.split(File.pathSeparator); + URL[] urls = new URL[entries.length]; + for (int i = 0; i < entries.length; i++) { + urls[i] = new File(entries[i]).toURI().toURL(); + } + generator.setImportClassLoader(new URLClassLoader(urls, null)); } else { File file = new File(arg); DefinitionFile content = generator.load(file); @@ -261,11 +1439,31 @@ public static void main(String[] args) throws ParseException, IOException, Insta if (out != null) { generator.setOut(out); } - generator.generate(plugin); + + try { + generator.generate(loadPlugins()); + } catch (GeneratorException ex) { + for (String error : ex.getErrors()) { + System.err.println("ERROR: " + error); + } + System.exit(1); + } + } + + /** + * Loads generator plugins via {@link ServiceLoader}. + */ + public static GeneratorPlugin loadPlugins() { + ServiceLoader pluginLoader = ServiceLoader.load(GeneratorPlugin.class); + GeneratorPlugin plugin = GeneratorPlugin.none(); + for (GeneratorPlugin p : pluginLoader) { + plugin = plugin.andThen(p); + } + return plugin; } private static void printHelp() { - System.err.println("Usage: java -jar " + Generator.class.getName() + " -out *"); + System.err.println("Usage: java -jar " + Generator.class.getName() + " -out [-resources ] [-ts ] [-I ]* [-cp ] *"); } private static File findBase(File protoFile, DefinitionFile content) { 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 672fbf33..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 @@ -3,8 +3,11 @@ */ package de.haumacher.msgbuf.generator; +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; @@ -14,6 +17,29 @@ */ public interface GeneratorPlugin { + /** + * Initializes the plug-in with file options. + * + * @param options The options of the current file to translate. + */ + default void init(Map options) { + // Ignore. + } + + /** + * Adds interfaces to the generated type. + * + * @param options + * The options from the top-level definition file. + * @param def + * The {@link MessageDef} that is being translated. + * @param generalizations + * The generalization list to extend. + */ + default void addInterfaces(Map options, MessageDef def, List generalizations) { + // No additional interfaces by default. + } + /** * Creates a {@link FileGenerator} that is expanded within the interface class. * @@ -34,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. */ @@ -53,6 +140,36 @@ default GeneratorPlugin andThen(GeneratorPlugin next) { GeneratorPlugin self = this; return new GeneratorPlugin() { + @Override + public void init(Map options) { + self.init(options); + next.init(options); + } + + @Override + public void addInterfaces(Map options, MessageDef def, List generalizations) { + self.addInterfaces(options, def, generalizations); + next.addInterfaces(options, def, generalizations); + } + + @Override + public void addFormats(Map 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) { return (out, indent) -> { diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageDefOperations.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageDefOperations.java new file mode 100644 index 00000000..5096214a --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageDefOperations.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2023 Bernhard Haumacher et al. All Rights Reserved. + */ +package de.haumacher.msgbuf.generator; + +import de.haumacher.msgbuf.generator.ast.Field; +import de.haumacher.msgbuf.generator.ast.MessageDef; + +/** + * Mix-in interface for {@link MessageDef}. + * + * @author Bernhard Haumacher + */ +public interface MessageDefOperations { + + MessageDef self(); + + default Field container() { + Field local = self().getFields().stream().filter(Field::isContainer).findAny().orElse(null); + if (local != null) { + return local; + } + + MessageDef generalization = self().getExtendedDef(); + if (generalization == null) { + return null; + } + + return generalization.container(); + } + +} 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 fb9a6686..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 @@ -4,7 +4,6 @@ package de.haumacher.msgbuf.generator; import static de.haumacher.msgbuf.generator.CodeConvention.*; -import static de.haumacher.msgbuf.generator.DefaultValueGenerator.*; import static de.haumacher.msgbuf.generator.TypeGenerator.*; import static de.haumacher.msgbuf.generator.util.CodeUtil.*; @@ -18,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; @@ -41,7 +41,8 @@ public class MessageGenerator extends AbstractMessageGenerator implements Defini private final NameTable _table; private final MessageDef _def; private final GeneratorPlugin _plugin; - + private final DefaultValueGenerator _defaultValues; + private boolean _graph; private boolean _json; private boolean _binary; @@ -50,25 +51,25 @@ public class MessageGenerator extends AbstractMessageGenerator implements Defini private boolean _visitEx; private boolean _typeKind; - private Map _options; private boolean _listener; private boolean _interface; /** * Creates a {@link MessageGenerator}. + * @param packageSuffix */ - public MessageGenerator(NameTable table, Map options, boolean isInterface, MessageDef def, GeneratorPlugin plugin) { - super(options); + public MessageGenerator(NameTable table, Map options, boolean isInterface, String packageSuffix, MessageDef def, GeneratorPlugin plugin) { + super(options, packageSuffix); _table = table; - _options = options; _interface = isInterface; _def = def; _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); @@ -122,15 +123,19 @@ protected void generate() { if (_def.getFile() != null) { QName packageName = _def.getFile().getPackage(); if (packageName != null) { - line("package " + packageName(packageName) + ";"); + line("package " + packageName(packageName) + (_packageSuffix == null ? "" : "." + _packageSuffix) + ";"); nl(); } modifier = ""; } else { modifier = _interface ? "" : "static"; } - docComment(_def.getComment()); - line((_interface || _noInterfaces ? "public" : ""), modifier, mkAbstract(), (_interface ? "interface" : "class"), (_interface || _noInterfaces ? typeName(_def) : implName(_def)), getExtends(), getImplements(), "{"); + if (_interface || _noInterfaces) { + docComment(_def.getComment()); + } else { + docComment("Implementation of {@link " + qTypeName(_def) + "}."); + } + line("public", modifier, mkAbstract(), (_interface ? "interface" : "class"), (_interface || _noInterfaces ? typeName(_def) : implName(_def)), getExtends(), getImplements(), "{"); generateClassContents(); nl(); line("}"); @@ -155,7 +160,13 @@ private String getExtends() { } } } else { - generalizations.add(_interface || _noInterfaces ? qTypeName(_def.getExtends()) : implName(_def.getExtendedDef())); + if (_interface || _noInterfaces) { + // For cross-file extensions, use resolved definition to get correct package casing + MessageDef extDef = _def.getExtendedDef(); + generalizations.add(extDef != null ? qTypeName(extDef) : qTypeName(_def.getExtends())); + } else { + generalizations.add(qImplName(_def.getExtendedDef())); + } } if (_interface) { @@ -164,7 +175,7 @@ private String getExtends() { } addMixins(generalizations); } - + return generalizationList("extends", generalizations); } @@ -180,7 +191,7 @@ private String getImplements() { } addMixins(generalizations); } else { - generalizations.add(typeName(_def)); + generalizations.add(qTypeName(_def)); } return generalizationList("implements", generalizations); @@ -200,6 +211,8 @@ private void addImplements(List generalizations) { } private void addMixins(List generalizations) { + _plugin.addInterfaces(getOptions(), _def, generalizations); + Option operations = _def.getOptions().get("Operations"); if (operations != null) { if (operations instanceof StringOption) { @@ -250,9 +263,15 @@ private void generateClassContents() { if (_typeKind) { generateTypeCodeEnum(); } + if (isOpenWorld() && _interface && _def.isAbstract() && _def.getExtendedDef() == null) { + generateOpenWorldRegistry(); + } if (_visitor) { generateVisitorInterface(); } + if (_visitor && isCrossFileExtension() && !_def.isAbstract() && (_interface || _noInterfaces)) { + generateExtensionVisitorInterface(); + } } generateInnerDefinitions(); if (_interface || _noInterfaces) { @@ -261,6 +280,14 @@ private void generateClassContents() { generateConstants(); if (!_interface) { + if (isOpenWorld() && _def.isAbstract() && _def.getExtendedDef() == null) { + nl(); + line("static {"); + { + line("de.haumacher.msgbuf.data.TypeRegistryLoader.ensureLoaded();"); + } + line("}"); + } generateFieldMembers(); generateConstructor(); } @@ -295,6 +322,10 @@ private void generateClassContents() { } if (_interface || _noInterfaces) { + if (_def.getOptions().get("Operations") != null) { + generateSelfAccess(); + } + include(_plugin.messageInterfaceContents(getOptions(), _def)); } @@ -306,11 +337,11 @@ private void generateClassContents() { private void generateTypeCodeEnum() { if (!_def.getSpecializations().isEmpty() && _def == getRoot(_def)) { nl(); - line("/** Type codes for the {@link " + typeName(_def) + "} hierarchy. */"); + line("/** Type codes for the {@link " + qTypeName(_def) + "} hierarchy. */"); line("public enum " + TYPE_KIND_NAME + " {"); for (MessageDef caseDef : concreteSpecializations(_def)) { nl(); - line("/** Type literal for {@link " + typeName(caseDef) + "}. */"); + line("/** Type literal for {@link " + qTypeName(caseDef) + "}. */"); line(typeKindConstant(caseDef) + ","); } line(";"); @@ -319,13 +350,41 @@ private void generateTypeCodeEnum() { } } + private void generateOpenWorldRegistry() { + nl(); + line("/** Registry for dynamically registered subtypes. */"); + line("static final java.util.Map> REGISTRY = new java.util.HashMap<>();"); + nl(); + line("/**"); + line(" * Registers a subtype factory for polymorphic deserialization."); + line(" */"); + line("static void register(String typeId, de.haumacher.msgbuf.data.Factory factory) {"); + { + line("REGISTRY.put(typeId, factory);"); + } + line("}"); + } + + private void generateExtensionVisitorInterface() { + nl(); + line("/** Extended visitor that can handle {@link " + typeName(_def) + "}. */"); + line("public interface Visitor extends " + qTypeName(getAbstractGeneralization()) + ".Visitor {"); + { + nl(); + line("/** Visit case for {@link " + typeName(_def) + "}. */"); + line("R visit(" + qTypeName(_def) + " self, A arg)" + onVisitEx(" throws E") + ";"); + } + nl(); + line("}"); + } + private void generateVisitorInterface() { if (_def.isAbstract()) { nl(); - line("/** Visitor interface for the {@link " + typeName(_def) + "} hierarchy.*/"); + line("/** Visitor interface for the {@link " + qTypeName(_def) + "} hierarchy.*/"); lineStart("public interface Visitor"); boolean first = true; - for (MessageDef specialization : _def.getSpecializations()) { + for (MessageDef specialization : localSpecializations(_def)) { if (!specialization.isAbstract()) { continue; } @@ -335,20 +394,20 @@ private void generateVisitorInterface() { } else { append(", "); } - append(typeName(specialization) + ".Visitor"); + append(qTypeName(specialization) + ".Visitor"); } append(" {"); nl(); { boolean hasCase = false; - for (MessageDef specialization : _def.getSpecializations()) { + for (MessageDef specialization : localSpecializations(_def)) { if (specialization.isAbstract()) { continue; } nl(); - line("/** Visit case for {@link " + typeName(specialization) + "}.*/"); - line("R visit(" + typeName(specialization) + " self, A arg)" + onVisitEx(" throws E") + ";"); + line("/** Visit case for {@link " + qTypeName(specialization) + "}.*/"); + line("R visit(" + qTypeName(specialization) + " self, A arg)" + onVisitEx(" throws E") + ";"); hasCase = true; } @@ -357,6 +416,12 @@ private void generateVisitorInterface() { nl(); line("// Pure sum interface."); } + + if (isOpenWorld()) { + nl(); + line("/** Fallback for visiting subtypes not known at compile time. */"); + line("R visitDefault(" + qTypeName(_def) + " self, A arg)" + onVisitEx(" throws E") + ";"); + } } nl(); line("}"); @@ -369,17 +434,45 @@ 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; } @Override public Void visit(MessageDef def, Void arg) { - include(new MessageGenerator(_table, _options, _interface, def, _plugin)); + include(new MessageGenerator(_table, getOptions(), _interface, _packageSuffix, def, _plugin)); return null; } @@ -387,9 +480,9 @@ private void generateFactoryMethod() { if (!_def.isAbstract()) { nl(); line("/**"); - line(" * Creates a {@link " + typeName(_def) + "} instance."); + line(" * Creates a {@link " + qTypeName(_def) + "} instance."); line(" */"); - line((_noInterfaces ? "public " : "") + "static " + typeName(_def) + " " + factoryName(_def) + "() {"); + line((_noInterfaces ? "public " : "") + "static " + qTypeName(_def) + " " + factoryName(_def) + "() {"); { line("return new " + qImplName(_def) + "();"); } @@ -401,20 +494,22 @@ private void generateConstants() { if (_interface || _noInterfaces) { if ((_json || _reflection) && !_def.isAbstract()) { nl(); - line("/** Identifier for the {@link " + typeName(_def) + "} type in JSON format. */"); - line((_noInterfaces ? "public " : "") + "static final String " + jsonTypeConstant(_def) + " = " + jsonTypeID(_def) + ";"); + line("/** Identifier for the {@link " + qTypeName(_def) + "} type in JSON format. */"); + line((_noInterfaces ? "public static final " : "") + "String " + jsonTypeConstant(_def) + " = " + jsonTypeID(_def) + ";"); } } if (_json || _reflection) { - if (_reflection == (_interface || _noInterfaces)) { + if (_interface || _noInterfaces) { + String modifier = _reflection ? (_noInterfaces ? "public " : "") : (_noInterfaces ? "private " : ""); + for (Field field : getFields()) { if (!_reflection && field.isTransient()) { continue; } nl(); line("/** @see #" + getterCall(field) + " */"); - line((_reflection ? (_noInterfaces ? "public " : "") : "private ") + "static final String " + constant(field) + " = " + getFieldNameString(field) + ";"); + line(modifier + (_noInterfaces ? "static final " : "") + "String " + constant(field) + " = " + getFieldNameString(field) + ";"); } } } @@ -422,7 +517,7 @@ private void generateConstants() { if (_binary && (_interface || _noInterfaces)) { if (!_def.isAbstract() && getRoot(_def).isAbstract()) { nl(); - line("/** Identifier for the {@link " + typeName(_def) + "} type in binary format. */"); + line("/** Identifier for the {@link " + qTypeName(_def) + "} type in binary format. */"); line("static final int " + mkBinaryTypeConstant(_def) + " = " + _def.getId() + ";"); } @@ -448,10 +543,10 @@ private void generateConstructor() { line(" * Creates a {@link " + implName(_def) + "} instance."); if (!_def.isAbstract()) { line(" *"); - line(" * @see " + typeName(_def) + "#" + factoryName(_def) + "()"); + line(" * @see " + qTypeName(_def) + "#" + factoryName(_def) + "()"); } line(" */"); - line("protected " + implName(_def) + "() {"); + line((_noInterfaces ? "protected " : "public ") + implName(_def) + "() {"); { line("super();"); } @@ -462,37 +557,99 @@ private void generateFieldMembers() { for (Field field : getFields()) { nl(); - if (field.isRepeated()) { + boolean isList = field.isRepeated(); + boolean isMap = field.getType() instanceof MapType; + if (isList || isMap) { Field reverseEnd = reverseEnd(field); boolean hasReverseEnd = reverseEnd != null; - if (_listener || hasReverseEnd) { - String qFieldTypeName = mkTypeWrapped(field.getType()); - line("private" + mkTransient(field) + mkFinal(field) + " " + mkType(field) + " " + fieldMemberName(field) + " = " + "new de.haumacher.msgbuf.util.ReferenceList<" + qFieldTypeName + ">() {"); + + Field container = field.container(); + boolean hasContainer = container != null; + + if (_listener || hasReverseEnd || container != null) { + Type type = field.getType(); + Type contentType = isList ? type : ((MapType) type).getValueType(); + String contentTypeWrapped = mkTypeWrapped(contentType); + String contentTypeImpl = mkTypeWrappedImpl(contentType); + String keyType = isList ? + "int" : + mkTypeWrapped(((MapType) type).getKeyType()); + + // Note: Anonymous type construction with omitted type arguments (<>) is not compatible with GWT. + String collectionType = isList ? + "de.haumacher.msgbuf.util.ReferenceList" + "<" + mkTypeWrapped(type) + ">" : + "de.haumacher.msgbuf.util.ReferenceMap" + "<" + mkTypeWrapped(((MapType) field.getType()).getKeyType()) + ", " + mkTypeWrapped(((MapType) type).getValueType()) + ">"; + line("private" + mkTransient(field) + mkFinal(field) + " " + mkType(field) + " " + fieldMemberName(field) + " = " + "new " + collectionType + "() {"); { line("@Override"); - line("protected void beforeAdd(int index, " + qFieldTypeName + " element) {"); + line("protected void beforeAdd(" + keyType + " " + "index" + ", " + contentTypeWrapped + " element) {"); { + if (hasContainer || hasReverseEnd) { + if (_noInterfaces) { + line(contentTypeWrapped + " added = element;"); + } else { + line(contentTypeImpl + " added = (" + contentTypeImpl + ") element;"); + } + } + + if (hasContainer) { + // Check early to not leave back inconsistent state upon error. + line(mkType(container) + " oldContainer = added." + getterName(container) + "();"); + line("if (oldContainer != null && oldContainer != " + implName(_def) + ".this) {"); + { + line("throw new IllegalStateException(\"Object may not be part of two different containers.\");"); + } + line("}"); + } + if (_listener) { - line("_listener.beforeAdd(" + implName(_def) + ".this, " + constant(field) + ", index, element);"); + line("_listener.beforeAdd(" + implName(_def) + ".this, " + constant(field) + ", " + "index" + ", element);"); } + + if (hasContainer) { + line("added." + internalSetterName(container) + "(" + implName(_def) + ".this);"); + } + if (hasReverseEnd) { - line("((" + mkTypeWrappedImpl(field.getType()) + ") element)." + adderName(reverseEnd) + "(" + implName(_def) + ".this);"); + line("added." + adderName(reverseEnd) + "(" + implName(_def) + ".this);"); } } line("}"); nl(); line("@Override"); - line("protected void afterRemove(int index, " + qFieldTypeName + " element) {"); + line("protected void afterRemove(" + keyType + " " + "index" + ", " + contentTypeWrapped + " element) {"); { + if (hasContainer || hasReverseEnd) { + if (_noInterfaces) { + line(contentTypeWrapped + " removed = element;"); + } else { + line(contentTypeImpl + " removed = (" + contentTypeImpl + ") element;"); + } + } + if (hasReverseEnd) { - line("((" + mkTypeWrappedImpl(field.getType()) + ") element)." + removerName(reverseEnd) + "(" + implName(_def) + ".this);"); + line("removed." + removerName(reverseEnd) + "(" + implName(_def) + ".this);"); + } + + if (hasContainer) { + line("removed." + internalSetterName(container) + "(null);"); } + if (_listener) { line("_listener.afterRemove(" + implName(_def) + ".this, " + constant(field) + ", index, element);"); } } line("}"); + + if (_listener) { + nl(); + + line("@Override"); + line("protected void afterChanged() {"); + line("_listener.afterChanged(" + implName(_def) + ".this, " + constant(field) + ");"); + line("}"); + } } line("};"); continue; @@ -506,7 +663,7 @@ private void generateFieldMembers() { private void generateKindLookup() { boolean hasSpecializations = !_def.getSpecializations().isEmpty(); boolean hasTypeLookup = !isBaseClass() || hasSpecializations; - + if (hasTypeLookup) { if (_interface) { if (isBaseClass()) { @@ -516,11 +673,20 @@ private void generateKindLookup() { } } else { if (_def.isAbstract()) { - if (isBaseClass()) { + if (_noInterfaces && isBaseClass()) { nl(); kindLookupComment(); line("public abstract " + TYPE_KIND_NAME + " kind();"); } + } 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() {"); + { + line("return null;"); + } + line("}"); } else { nl(); line("@Override"); @@ -595,12 +761,15 @@ private void accessorSetter(Field field, boolean override) { } line(myType() + " " + setterName(field) + "(" + mkTypeReadOnly(field) + " " + "value" + ");"); } - } else { + } else if (!(field.isDerived() && override)) { nl(); - if (!field.isDerived()) { + if (field.isDerived()) { + docComment("Internal setter for updating derived field."); + } else { if (!override && _noInterfaces) { setterDoc(field); } else { + // Only in interface for non-derived fields, therefore no override necessary for derived fields. line("@Override"); } } @@ -640,27 +809,78 @@ private void accessorSetterImpl(Field field) { Field reverseEnd = reverseEnd(field); boolean hasReverseEnd = reverseEnd != null; + Field container = field.container(); + boolean hasContainer = container != null; + + if (hasContainer || hasReverseEnd) { + if (_noInterfaces) { + line(mkTypeWrapped(type) + " before = " + fieldMemberName(field) +";"); + line(mkTypeWrapped(type) + " after = value;"); + } else { + line(mkTypeWrappedImpl(type) + " before = (" + mkTypeWrappedImpl(type) + ") " + fieldMemberName(field) +";"); + line(mkTypeWrappedImpl(type) + " after = (" + mkTypeWrappedImpl(type) + ") value;"); + } + } + + if (hasContainer) { + // Check early to not leave back inconsistent state upon error. + line("if (after != null) {"); + { + line(mkType(container) + " oldContainer = after." + getterName(container) + "();"); + line("if (oldContainer != null && oldContainer != this) {"); + { + line("throw new IllegalStateException(\"Object may not be part of two different containers.\");"); + } + line("}"); + } + line("}"); + } + if (_listener) { line("_listener.beforeSet(this, " + constant(field) + ", value);"); } - if (hasReverseEnd) { - line("if (" + fieldMemberName(field) + " != null) {"); + if (hasContainer || hasReverseEnd) { + line("if (before != null) {"); { - line("((" + mkTypeWrappedImpl(type) + ") " + fieldMemberName(field) + ")." + removerName(reverseEnd) + "(this);"); + if (hasContainer) { + line("before." + internalSetterName(container) + "(null);"); + } + + if (hasReverseEnd) { + line("before." + removerName(reverseEnd) + "(this);"); + } } line("}"); } + if (field.isContainer()) { + line("if (value != null && " + fieldMemberName(field) + " != null) {"); + { + line("throw new IllegalStateException(\"Object may not be part of two different containers.\");"); + } + line("}"); + } + line(fieldMemberName(field) + " = " + "value" + ";"); - if (hasReverseEnd) { - line("if (value != null) {"); + if (hasContainer || hasReverseEnd) { + line("if (after != null) {"); { - line("((" + mkTypeWrappedImpl(type) + ") value)." + adderName(reverseEnd) + "(this);"); + if (hasReverseEnd) { + line("after." + adderName(reverseEnd) + "(this);"); + } + + if (hasContainer) { + line("after." + internalSetterName(container) + "(this);"); + } } line("}"); } + + if (_listener) { + line("_listener.afterChanged(this, " + constant(field) + ");"); + } } } line("}"); @@ -864,7 +1084,7 @@ private String setterModifier(Field field) { private void adderInitNullable(Field field) { if (Util.isNullable(field)) { - line("if (" + fieldMemberName(field) + " == null) " + fieldMemberName(field) + " = " + mkDefaultValueNonNullable(field) + ";"); + line("if (" + fieldMemberName(field) + " == null) " + fieldMemberName(field) + " = " + _defaultValues.mkDefaultValueNonNullable(field) + ";"); } } @@ -960,16 +1180,24 @@ private void generateReflection() { } private void reflectionType() { - if (!(_reflection && _def.isAbstract())) { - nl(); - if (_def.isAbstract()) { + if (_def.isAbstract()) { + if (!_def.hasExtendedDef() && !_reflection) { + // Otherwise, the interface is inherited from ReflectiveDataObject. if (_interface || _noInterfaces) { + nl(); jsonTypeDoc(); line((_noInterfaces ? "public abstract " : "") + "String jsonType();"); } - } else { + } + } else { + if (_reflection || _def.hasExtendedDef() || !_def.getSpecializations().isEmpty()) { if (!_interface) { - line("@Override"); + nl(); + if (_reflection || _def.hasExtendedDef()) { + line("@Override"); + } else { + jsonTypeDoc(); + } line("public String jsonType() {"); { line("return " + jsonTypeConstant(_def) + ";"); @@ -985,10 +1213,20 @@ private void jsonTypeDoc() { } private void reflectionPropertiesConstant() { + MessageDef anchestor = _def.getExtendedDef(); + while (anchestor != null && !hasFields(anchestor)) { + anchestor = anchestor.getExtendedDef(); + } + nl(); - line("private static java.util.List PROPERTIES = java.util.Collections.unmodifiableList("); + if (anchestor != null) { + line("@SuppressWarnings(\"hiding\")"); + } + String propsVisibility = (isOpenWorld() || isCrossFileExtension()) ? "protected " : ""; + line(propsVisibility + "static final java.util.List PROPERTIES;"); + line("static {"); { - line("java.util.Arrays.asList("); + line("java.util.List local = java.util.Arrays.asList("); { boolean first = true; for (Field field : getFields()) { @@ -1000,10 +1238,58 @@ private void reflectionPropertiesConstant() { } lineStart(constant(field)); } + append(");"); + nl(); + } + + if (anchestor != null) { + line("java.util.List tmp = new java.util.ArrayList<>();"); + line("tmp.addAll(" + qImplName(anchestor) + ".PROPERTIES" + ");"); + line("tmp.addAll(local);"); + line("PROPERTIES = java.util.Collections.unmodifiableList(tmp);"); + } else { + line("PROPERTIES = java.util.Collections.unmodifiableList(local);"); + } + } + line("}"); + + nl(); + if (anchestor != null) { + line("@SuppressWarnings(\"hiding\")"); + } + line(propsVisibility + "static final java.util.Set TRANSIENT_PROPERTIES;"); + line("static {"); + { + line("java.util.HashSet tmp = new java.util.HashSet<>();"); + + if (anchestor != null) { + line("tmp.addAll(" + qImplName(anchestor) + ".TRANSIENT_PROPERTIES" + ");"); + } + line("tmp.addAll(java.util.Arrays.asList("); + { + boolean first = true; + for (Field field : getFields()) { + if (!field.isTransient()) { + continue; + } + if (first) { + first = false; + } else { + append(", "); + nl(); + } + lineStart(constant(field)); + } + if (first) { + lineStart(""); + } append("));"); nl(); } + + line("TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp);"); } + line("}"); } private void reflectionProperties() { @@ -1014,6 +1300,14 @@ private void reflectionProperties() { line("return PROPERTIES;"); } line("}"); + + nl(); + line("@Override"); + line("public java.util.Set transientProperties() {"); + { + line("return TRANSIENT_PROPERTIES;"); + } + line("}"); } private void reflectionGet() { @@ -1030,7 +1324,7 @@ private void reflectionGet() { // To complicated to select the correct super type. line("default: return null;"); } else { - line("default: return " + typeName(_def) + ".super.get(field);"); + line("default: return " + qTypeName(_def) + ".super.get(field);"); } } else { line("default: return super.get(field);"); @@ -1084,14 +1378,48 @@ private void generateJson() { line("int id = in.nextInt();"); } line("switch (type) {"); - for (MessageDef specialization : Util.concreteTransitiveSpecializations(_def)) { + for (MessageDef specialization : concreteSpecializations(_def)) { if (_graph) { - line("case " + jsonTypeConstantRef(specialization) + ": result = " + typeName(specialization) + ".create(); break;"); + line("case " + jsonTypeConstantRef(specialization) + ": result = " + qTypeName(specialization) + ".create(); break;"); } else { line("case " + jsonTypeConstantRef(specialization) + ": result = " + qTypeName(specialization) + "." + readerName(specialization) + "(in); break;"); } } - line("default: in.skipValue(); result = null; break;"); + if (isOpenWorld()) { + line("default: {"); + { + // 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 {"); + { + line("in.skipValue();"); + line("result = null;"); + } + line("}"); + } + line("} break;"); + } else { + line("default: in.skipValue(); result = null; break;"); + } line("}"); if (_graph) { line("if (result != null) {"); @@ -1287,13 +1615,15 @@ private void jsonReadField(Field field) { if (field.isRepeated()) { line("case " + constant(field) + ": {"); { + line(mkType(field)+ " newValue = new java.util.ArrayList<>();"); line("in.beginArray();"); line("while (in.hasNext()) {"); { - line(adderName(field) + "(" + jsonReadEntry(type) + ");"); + line("newValue.add(" + jsonReadEntry(type) + ");"); } line("}"); line("in.endArray();"); + line(setterName(field) + "(newValue);"); } line("}"); line("break;"); @@ -1304,20 +1634,23 @@ private void jsonReadField(Field field) { Type keyType = mapType.getKeyType(); Type valueType = mapType.getValueType(); if (keyType instanceof PrimitiveType && ((PrimitiveType) keyType).getKind() == Kind.STRING) { + line(mkType(field)+ " newValue = new java.util.LinkedHashMap<>();"); line("in.beginObject();"); line("while (in.hasNext()) {"); { - line(adderName(field) + "(in.nextName(), " + jsonReadEntry(valueType) + ");"); + line("newValue.put(in.nextName(), " + jsonReadEntry(valueType) + ");"); } line("}"); line("in.endObject();"); + line(setterName(field) + "(newValue);"); } else { + line(mkType(field)+ " newValue = new java.util.LinkedHashMap<>();"); line("in.beginArray();"); line("while (in.hasNext()) {"); { line("in.beginObject();"); - line(mkType(keyType) + " key = " + mkDefaultValue(keyType) + ";"); - line(mkType(valueType) + " value = " + mkDefaultValue(valueType) + ";"); + line(mkType(keyType) + " key = " + _defaultValues.mkDefaultValue(keyType) + ";"); + line(mkType(valueType) + " value = " + _defaultValues.mkDefaultValue(valueType) + ";"); line("while (in.hasNext()) {"); { line("switch (in.nextName()) {"); @@ -1327,11 +1660,12 @@ private void jsonReadField(Field field) { line("}"); } line("}"); - line(adderName(field) + "(key, value);"); + line("newValue.put(key, value);"); line("in.endObject();"); } line("}"); line("in.endArray();"); + line(setterName(field) + "(newValue);"); } } line("break;"); @@ -1393,8 +1727,11 @@ private String jsonType(PrimitiveType.Kind primitive) { case BYTES: return "de.haumacher.msgbuf.json.JsonUtil.nextBinaryOptional(in)"; - } - + + case JSON: + return "de.haumacher.msgbuf.json.JsonUtil.nextJsonValue(in)"; + } + throw new RuntimeException("No such type: " + primitive); } @@ -1409,6 +1746,10 @@ private void jsonOutValue(Type type, String x, int depth) { line("de.haumacher.msgbuf.json.JsonUtil.writeBinaryOptional(out, " + x + ");"); break; } + case JSON: { + line("de.haumacher.msgbuf.json.JsonUtil.writeJsonValue(out, " + x + ");"); + break; + } default: { line("out.value(" + x + ");"); break; @@ -1503,7 +1844,7 @@ private void binaryTypeId() { } private void typeIdDoc() { - line("/** The binary identifier for this concrete type in the polymorphic {@link " + typeName(_def) + "} hierarchy. */"); + line("/** The binary identifier for this concrete type in the polymorphic {@link " + qTypeName(_def) + "} hierarchy. */"); } private void binaryWrite() { @@ -1549,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) + ");"); @@ -1571,7 +1916,7 @@ private void binaryWrite() { binaryWriteValue(field.getType(), getterCall(field)); } } - if (nullable) { + if (nullable || nullBytes) { line("}"); } } @@ -1583,11 +1928,48 @@ private void binaryWrite() { private void binaryWriteValue(Type type, String x) { if (type instanceof PrimitiveType) { - 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);"); - } else { - // TODO + } else if (type instanceof MapType) { + MapType mapType = (MapType) type; + Type keyType = mapType.getKeyType(); + Type valueType = mapType.getValueType(); + line("{"); + { + String entry = "entry"; + line("out.beginArray(de.haumacher.msgbuf.binary.DataType.OBJECT, " + x + ".size());"); + line("for (" + mkEntryType(mapType) + " " + entry + " : " + x + ".entrySet()) {"); + { + line("out.beginObject();"); + line("out.name(1);"); + binaryWriteValue(keyType, entry + ".getKey()"); + line("out.name(2);"); + binaryWriteValue(valueType, entry + ".getValue()"); + line("out.endObject();"); + } + line("}"); + line("out.endArray();"); + } + line("}"); } } @@ -1604,7 +1986,7 @@ private void binaryRead() { line("int type = in.nextInt();"); line(thisType() + " result;"); line("switch (type) {"); - for (MessageDef specialization : Util.concreteTransitiveSpecializations(_def)) { + for (MessageDef specialization : concreteSpecializations(_def)) { line("case " + mkBinaryTypeConstantRef(specialization) + ": result = " + qImplName(specialization) + "." + readerNameContent(specialization) + "(in); break;"); } line("default: result = null; while (in.hasNext()) {in.skipValue(); }"); @@ -1672,11 +2054,11 @@ private void binaryRead() { } private String thisType() { - return typeName(_def); + return qTypeName(_def); } private String myType() { - return typeName(_def); + return qTypeName(_def); } private void generateChain() { @@ -1716,8 +2098,8 @@ private void binaryReadField(Field field) { line("while (in.hasNext()) {"); { line("in.beginObject();"); - line(mkType(keyType) + " key = " + mkDefaultValue(keyType) + ";"); - line(mkType(valueType) + " value = " + mkDefaultValue(valueType) + ";"); + line(mkType(keyType) + " key = " + _defaultValues.mkDefaultValue(keyType) + ";"); + line(mkType(valueType) + " value = " + _defaultValues.mkDefaultValue(valueType) + ";"); line("while (in.hasNext()) {"); { line("switch (in.nextName()) {"); @@ -1753,7 +2135,7 @@ else if (type instanceof CustomType) { } private String mkBinaryTypeConstantRef(MessageDef def) { - return typeName(def) + "." + mkBinaryTypeConstant(def); + return qTypeName(def) + "." + mkBinaryTypeConstant(def); } private String mkBinaryReadValue(Kind kind) { @@ -1789,8 +2171,11 @@ private String mkBinaryReadValue(Kind kind) { case BYTES: return "in.nextBinary()"; - } - + + case JSON: + return "de.haumacher.msgbuf.json.JsonUtil.fromJsonValue(de.haumacher.msgbuf.json.value.JsonValue.readJsonValue(in))"; + } + throw new RuntimeException("No such type: " + kind); } @@ -1842,11 +2227,24 @@ private DataType mkBinaryType(PrimitiveType.Kind primitive) { case BYTES: return DataType.BINARY; - } - + + case JSON: + return DataType.OBJECT; + } + throw new RuntimeException("No such type: " + primitive); } + private void generateSelfAccess() { + nl(); + line("@Override"); + line((_noInterfaces ? "public" : "default") + " " + typeName(_def) + " self() {"); + { + line("return this;"); + } + line("}"); + } + private void generateVisitMethods() { if (_def.isAbstract()) { if (_interface || _noInterfaces) { @@ -1861,10 +2259,27 @@ private void generateVisitMethods() { if (!_interface) { nl(); line("@Override"); - line("public" + (_def.isAbstract() ? " final" : "") + " R visit(" + typeName(gen) + ".Visitor v, A arg) " + onVisitEx("throws E ") + "{"); + line("public" + (_def.isAbstract() ? " final" : "") + " R visit(" + qTypeName(gen) + ".Visitor v, A arg) " + onVisitEx("throws E ") + "{"); { if (_def.isAbstract()) { - line("return visit((" + typeName(_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) {"); + { + line("return ((" + qTypeName(_def) + ".Visitor) v).visit(this, arg);"); + } + line("}"); + line("return v.visitDefault(this, arg);"); } else { line("return v.visit(this, arg);"); } @@ -1952,7 +2367,7 @@ private String mkFinal(Field field) { } private String mkInitializer(Field field) { - return " = " + mkDefaultValue(field); + return " = " + _defaultValues.mkDefaultValue(field); } static QName qName(String name) { @@ -1984,15 +2399,45 @@ private static Field getReverseField(MessageDef def, String name) { } static Field getLocalReverseField(MessageDef def, String name) { - return def.getFields().stream().filter(f -> hasReverseName(f, name)).findFirst().orElse(null); + return def.getFields().stream().filter(f -> f.isReverseOf(name)).findFirst().orElse(null); + } + + private boolean isOpenWorld() { + return isTrue(getOptions().get("OpenWorld"), false); } - private static boolean hasReverseName(Field f, String name) { - StringOption reverseOption = (StringOption) f.getOptions().get("Reverse"); - if (reverseOption == null) { - return false; + private String getOpenWorldRoot() { + MessageDef current = _def; + while (current.getExtendedDef() != null) { + current = current.getExtendedDef(); } - return reverseOption.getValue().equals(name); + return qTypeName(current); + } + + private boolean isCrossFileExtension() { + MessageDef gen = getAbstractGeneralization(); + if (gen == null) return false; + 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, 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 11876928..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,8 +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; @@ -16,34 +22,56 @@ 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); } @@ -54,17 +82,8 @@ public Void visit(MessageDef self, Void arg) { return null; } - private void enterDef(Definition def) { - _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); @@ -73,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) { @@ -89,31 +112,252 @@ 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) { - return _definitionByName.get(Util.last(name)); + 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; + } + + /** + * Resolves the given name in the given context without reporting an error. + * + * @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. + * + * @see #resolve(DefinitionFile, MessageDef, QName) + */ + public Definition resolve(MessageDef context, QName name) { + return resolve(context == null ? null : Util.definingFile(context), context, name); + } + + /** + * 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); + } + + 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++) { + String nextName = name.getNames().get(n); + Definition inner = lookupInner(base, nextName); + if (inner == null) { + resolved = false; + break; + } + base = inner; + } + if (resolved) { + return base; + } + } + + // Try as package-qualified name. + // Try progressively longer package prefixes: a.b.c.Type -> try "a.b.c", "a.b", "a" as package + List names = name.getNames(); + for (int split = names.size() - 1; split >= 1; split--) { + String pkgName = String.join(".", names.subList(0, split)); + Package pkg = _packageByName.get(pkgName); + if (pkg != null) { + String typeName = names.get(split); + Definition found = pkg._definitionsByName.get(typeName); + if (found != null) { + // Resolve remaining parts (if any) as inner definitions + for (int n = split + 1; n < names.size(); n++) { + found = lookupInner(found, names.get(n)); + if (found == null) break; + } + if (found != null) return found; + } + } + } + + 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(); + if (match.isPresent()) { + return match.get(); + } else { + return null; + } + } else { + return null; + } + } + + /** + * 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 List.of(inner); + } + context = context.getOuter(); + } + + 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/TypeGenerator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/TypeGenerator.java index 458a35a9..3c8ddb20 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/TypeGenerator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/TypeGenerator.java @@ -8,6 +8,7 @@ import java.util.function.Function; import de.haumacher.msgbuf.generator.ast.CustomType; +import de.haumacher.msgbuf.generator.ast.Definition; import de.haumacher.msgbuf.generator.ast.Field; import de.haumacher.msgbuf.generator.ast.MapType; import de.haumacher.msgbuf.generator.ast.PrimitiveType; @@ -24,16 +25,19 @@ public class TypeGenerator implements Type.Visitor { /** * Singleton {@link TypeGenerator} instance. */ - public static final TypeGenerator INSTANCE = new TypeGenerator(CodeConvention::typeName); + public static final TypeGenerator INSTANCE = new TypeGenerator(null, CodeConvention::typeName); /** * Singleton {@link TypeGenerator} instance. */ - public static final TypeGenerator IMPL_INSTANCE = new TypeGenerator(CodeConvention::implName); + public static final TypeGenerator IMPL_INSTANCE = new TypeGenerator(CodeConvention.IMPL_PACKAGE_SUFFIX, CodeConvention::implName); private Function _typeNameConvention; - private TypeGenerator(Function typeNameConvention) { + private String _packageSuffix; + + private TypeGenerator(String packageSuffix, Function typeNameConvention) { + _packageSuffix = packageSuffix; _typeNameConvention = typeNameConvention; } @@ -72,7 +76,11 @@ public String visit(MapType type, Boolean wrapped) { @Override public String visit(CustomType type, Boolean wrapped) { - return qName(type.getName(), _typeNameConvention); + Definition definition = type.getDefinition(); + if (definition == null) { + return qName(type.getName()); + } + return qName(_packageSuffix, definition, _typeNameConvention); } @Override @@ -100,6 +108,8 @@ public String visit(PrimitiveType type, Boolean wrapped) { return wrapped ? "Long" : "long"; case STRING: return "String"; + case JSON: + return "Object"; } throw new RuntimeException("No such type: " + type.getKind()); } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Constant.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Constant.java index b304d4ac..af26ed25 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Constant.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Constant.java @@ -5,22 +5,22 @@ * * @see EnumDef#getConstants() */ -public class Constant extends Part { +public class Constant extends de.haumacher.msgbuf.generator.ast.Part { /** - * Creates a {@link Constant} instance. + * Creates a {@link de.haumacher.msgbuf.generator.ast.Constant} instance. */ - public static Constant create() { + public static de.haumacher.msgbuf.generator.ast.Constant create() { return new de.haumacher.msgbuf.generator.ast.Constant(); } - /** Identifier for the {@link Constant} type in JSON format. */ + /** Identifier for the {@link de.haumacher.msgbuf.generator.ast.Constant} type in JSON format. */ public static final String CONSTANT__TYPE = "Constant"; /** * Creates a {@link Constant} instance. * - * @see Constant#create() + * @see de.haumacher.msgbuf.generator.ast.Constant#create() */ protected Constant() { super(); @@ -32,37 +32,37 @@ public TypeKind kind() { } @Override - public Constant setName(String value) { + public de.haumacher.msgbuf.generator.ast.Constant setName(String value) { internalSetName(value); return this; } @Override - public Constant setIndex(int value) { + public de.haumacher.msgbuf.generator.ast.Constant setIndex(int value) { internalSetIndex(value); return this; } @Override - public Constant setOwner(Definition value) { + public de.haumacher.msgbuf.generator.ast.Constant setOwner(de.haumacher.msgbuf.generator.ast.Definition value) { internalSetOwner(value); return this; } @Override - public Constant setComment(String value) { + public de.haumacher.msgbuf.generator.ast.Constant setComment(String value) { internalSetComment(value); return this; } @Override - public Constant setOptions(java.util.Map value) { + public de.haumacher.msgbuf.generator.ast.Constant setOptions(java.util.Map value) { internalSetOptions(value); return this; } @Override - public Constant putOption(String key, Option value) { + public de.haumacher.msgbuf.generator.ast.Constant putOption(String key, de.haumacher.msgbuf.generator.ast.Option value) { internalPutOption(key, value); return this; } @@ -73,14 +73,14 @@ public String jsonType() { } /** Reads a new instance from the given reader. */ - public static Constant readConstant(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + public static de.haumacher.msgbuf.generator.ast.Constant readConstant(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { de.haumacher.msgbuf.generator.ast.Constant result = new de.haumacher.msgbuf.generator.ast.Constant(); result.readContent(in); return result; } @Override - public R visit(Part.Visitor v, A arg) { + public R visit(de.haumacher.msgbuf.generator.ast.Part.Visitor v, A arg) { return v.visit(this, arg); } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/CustomType.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/CustomType.java index 7e07ede9..1017f7cd 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/CustomType.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/CustomType.java @@ -5,32 +5,32 @@ * * A custom type is either a {@link EnumDef}, or a {@link MessageDef}. */ -public class CustomType extends Type { +public class CustomType extends de.haumacher.msgbuf.generator.ast.Type { /** - * Creates a {@link CustomType} instance. + * Creates a {@link de.haumacher.msgbuf.generator.ast.CustomType} instance. */ - public static CustomType create() { + public static de.haumacher.msgbuf.generator.ast.CustomType create() { return new de.haumacher.msgbuf.generator.ast.CustomType(); } - /** Identifier for the {@link CustomType} type in JSON format. */ + /** Identifier for the {@link de.haumacher.msgbuf.generator.ast.CustomType} type in JSON format. */ public static final String CUSTOM_TYPE__TYPE = "CustomType"; /** @see #getName() */ - public static final String NAME = "name"; + public static final String NAME__PROP = "name"; /** @see #getDefinition() */ - public static final String DEFINITION = "definition"; + public static final String DEFINITION__PROP = "definition"; - private QName _name = null; + private de.haumacher.msgbuf.generator.ast.QName _name = null; - private transient Definition _definition = null; + private transient de.haumacher.msgbuf.generator.ast.Definition _definition = null; /** * Creates a {@link CustomType} instance. * - * @see CustomType#create() + * @see de.haumacher.msgbuf.generator.ast.CustomType#create() */ protected CustomType() { super(); @@ -44,22 +44,23 @@ public TypeKind kind() { /** * The name of the reference type. */ - public final QName getName() { + public final de.haumacher.msgbuf.generator.ast.QName getName() { return _name; } /** * @see #getName() */ - public CustomType setName(QName value) { + public de.haumacher.msgbuf.generator.ast.CustomType setName(de.haumacher.msgbuf.generator.ast.QName value) { internalSetName(value); return this; } /** Internal setter for {@link #getName()} without chain call utility. */ - protected final void internalSetName(QName value) { - _listener.beforeSet(this, NAME, value); + protected final void internalSetName(de.haumacher.msgbuf.generator.ast.QName value) { + _listener.beforeSet(this, NAME__PROP, value); _name = value; + _listener.afterChanged(this, NAME__PROP); } /** @@ -72,22 +73,23 @@ public final boolean hasName() { /** * Resolved reference of the {@link Definition} defining the {@link #getName() referenced type}. */ - public final Definition getDefinition() { + public final de.haumacher.msgbuf.generator.ast.Definition getDefinition() { return _definition; } /** * @see #getDefinition() */ - public CustomType setDefinition(Definition value) { + public de.haumacher.msgbuf.generator.ast.CustomType setDefinition(de.haumacher.msgbuf.generator.ast.Definition value) { internalSetDefinition(value); return this; } /** Internal setter for {@link #getDefinition()} without chain call utility. */ - protected final void internalSetDefinition(Definition value) { - _listener.beforeSet(this, DEFINITION, value); + protected final void internalSetDefinition(de.haumacher.msgbuf.generator.ast.Definition value) { + _listener.beforeSet(this, DEFINITION__PROP, value); _definition = value; + _listener.afterChanged(this, DEFINITION__PROP); } /** @@ -102,21 +104,37 @@ public String jsonType() { return CUSTOM_TYPE__TYPE; } - private static java.util.List PROPERTIES = java.util.Collections.unmodifiableList( - java.util.Arrays.asList( - NAME, - DEFINITION)); + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + NAME__PROP, + DEFINITION__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + DEFINITION__PROP)); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } @Override public java.util.List properties() { return PROPERTIES; } + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + @Override public Object get(String field) { switch (field) { - case NAME: return getName(); - case DEFINITION: return getDefinition(); + case NAME__PROP: return getName(); + case DEFINITION__PROP: return getDefinition(); default: return super.get(field); } } @@ -124,14 +142,14 @@ public Object get(String field) { @Override public void set(String field, Object value) { switch (field) { - case NAME: internalSetName((QName) value); break; - case DEFINITION: internalSetDefinition((Definition) value); break; + case NAME__PROP: internalSetName((de.haumacher.msgbuf.generator.ast.QName) value); break; + case DEFINITION__PROP: internalSetDefinition((de.haumacher.msgbuf.generator.ast.Definition) value); break; default: super.set(field, value); break; } } /** Reads a new instance from the given reader. */ - public static CustomType readCustomType(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + public static de.haumacher.msgbuf.generator.ast.CustomType readCustomType(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { de.haumacher.msgbuf.generator.ast.CustomType result = new de.haumacher.msgbuf.generator.ast.CustomType(); result.readContent(in); return result; @@ -141,7 +159,7 @@ public static CustomType readCustomType(de.haumacher.msgbuf.json.JsonReader in) protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { super.writeFields(out); if (hasName()) { - out.name(NAME); + out.name(NAME__PROP); getName().writeTo(out); } } @@ -149,13 +167,13 @@ protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java. @Override protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { switch (field) { - case NAME: setName(de.haumacher.msgbuf.generator.ast.QName.readQName(in)); break; + case NAME__PROP: setName(de.haumacher.msgbuf.generator.ast.QName.readQName(in)); break; default: super.readField(in, field); } } @Override - public R visit(Type.Visitor v, A arg) { + public R visit(de.haumacher.msgbuf.generator.ast.Type.Visitor v, A arg) { return v.visit(this, arg); } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Definition.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Definition.java index cd3cca32..f2804f4f 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Definition.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Definition.java @@ -3,33 +3,33 @@ /** * Base class of a definition in a {@link DefinitionFile}. */ -public abstract class Definition extends DefinitionBase { +public abstract class Definition extends de.haumacher.msgbuf.generator.ast.DefinitionBase { - /** Visitor interface for the {@link Definition} hierarchy.*/ + /** Visitor interface for the {@link de.haumacher.msgbuf.generator.ast.Definition} hierarchy.*/ public interface Visitor { - /** Visit case for {@link EnumDef}.*/ - R visit(EnumDef self, A arg); + /** Visit case for {@link de.haumacher.msgbuf.generator.ast.EnumDef}.*/ + R visit(de.haumacher.msgbuf.generator.ast.EnumDef self, A arg); - /** Visit case for {@link MessageDef}.*/ - R visit(MessageDef self, A arg); + /** Visit case for {@link de.haumacher.msgbuf.generator.ast.MessageDef}.*/ + R visit(de.haumacher.msgbuf.generator.ast.MessageDef self, A arg); } /** @see #getName() */ - public static final String NAME = "name"; + public static final String NAME__PROP = "name"; /** @see #getFile() */ - public static final String FILE = "file"; + public static final String FILE__PROP = "file"; /** @see #getOuter() */ - public static final String OUTER = "outer"; + public static final String OUTER__PROP = "outer"; private String _name = ""; - private transient DefinitionFile _file = null; + private transient de.haumacher.msgbuf.generator.ast.DefinitionFile _file = null; - private transient MessageDef _outer = null; + private transient de.haumacher.msgbuf.generator.ast.MessageDef _outer = null; /** * Creates a {@link Definition} instance. @@ -48,36 +48,38 @@ public final String getName() { /** * @see #getName() */ - public Definition setName(String value) { + public de.haumacher.msgbuf.generator.ast.Definition setName(String value) { internalSetName(value); return this; } /** Internal setter for {@link #getName()} without chain call utility. */ protected final void internalSetName(String value) { - _listener.beforeSet(this, NAME, value); + _listener.beforeSet(this, NAME__PROP, value); _name = value; + _listener.afterChanged(this, NAME__PROP); } /** * Reference back to the {@link DefinitionFile} that contains this definition. */ - public final DefinitionFile getFile() { + public final de.haumacher.msgbuf.generator.ast.DefinitionFile getFile() { return _file; } /** * @see #getFile() */ - public Definition setFile(DefinitionFile value) { + public de.haumacher.msgbuf.generator.ast.Definition setFile(de.haumacher.msgbuf.generator.ast.DefinitionFile value) { internalSetFile(value); return this; } /** Internal setter for {@link #getFile()} without chain call utility. */ - protected final void internalSetFile(DefinitionFile value) { - _listener.beforeSet(this, FILE, value); + protected final void internalSetFile(de.haumacher.msgbuf.generator.ast.DefinitionFile value) { + _listener.beforeSet(this, FILE__PROP, value); _file = value; + _listener.afterChanged(this, FILE__PROP); } /** @@ -94,22 +96,23 @@ public final boolean hasFile() { * The value is null for top-level defintions, see {@link #getFile()}. *

*/ - public final MessageDef getOuter() { + public final de.haumacher.msgbuf.generator.ast.MessageDef getOuter() { return _outer; } /** * @see #getOuter() */ - public Definition setOuter(MessageDef value) { + public de.haumacher.msgbuf.generator.ast.Definition setOuter(de.haumacher.msgbuf.generator.ast.MessageDef value) { internalSetOuter(value); return this; } /** Internal setter for {@link #getOuter()} without chain call utility. */ - protected final void internalSetOuter(MessageDef value) { - _listener.beforeSet(this, OUTER, value); + protected final void internalSetOuter(de.haumacher.msgbuf.generator.ast.MessageDef value) { + _listener.beforeSet(this, OUTER__PROP, value); _outer = value; + _listener.afterChanged(this, OUTER__PROP); } /** @@ -120,40 +123,63 @@ public final boolean hasOuter() { } @Override - public Definition setComment(String value) { + public de.haumacher.msgbuf.generator.ast.Definition setComment(String value) { internalSetComment(value); return this; } @Override - public Definition setOptions(java.util.Map value) { + public de.haumacher.msgbuf.generator.ast.Definition setOptions(java.util.Map value) { internalSetOptions(value); return this; } @Override - public Definition putOption(String key, Option value) { + public de.haumacher.msgbuf.generator.ast.Definition putOption(String key, de.haumacher.msgbuf.generator.ast.Option value) { internalPutOption(key, value); return this; } - private static java.util.List PROPERTIES = java.util.Collections.unmodifiableList( - java.util.Arrays.asList( - NAME, - FILE, - OUTER)); + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + NAME__PROP, + FILE__PROP, + OUTER__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(de.haumacher.msgbuf.generator.ast.DefinitionBase.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(de.haumacher.msgbuf.generator.ast.DefinitionBase.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + FILE__PROP, + OUTER__PROP)); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } @Override public java.util.List properties() { return PROPERTIES; } + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + @Override public Object get(String field) { switch (field) { - case NAME: return getName(); - case FILE: return getFile(); - case OUTER: return getOuter(); + case NAME__PROP: return getName(); + case FILE__PROP: return getFile(); + case OUTER__PROP: return getOuter(); default: return super.get(field); } } @@ -161,16 +187,16 @@ public Object get(String field) { @Override public void set(String field, Object value) { switch (field) { - case NAME: internalSetName((String) value); break; - case FILE: internalSetFile((DefinitionFile) value); break; - case OUTER: internalSetOuter((MessageDef) value); break; + case NAME__PROP: internalSetName((String) value); break; + case FILE__PROP: internalSetFile((de.haumacher.msgbuf.generator.ast.DefinitionFile) value); break; + case OUTER__PROP: internalSetOuter((de.haumacher.msgbuf.generator.ast.MessageDef) value); break; default: super.set(field, value); break; } } /** Reads a new instance from the given reader. */ - public static Definition readDefinition(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { - Definition result; + public static de.haumacher.msgbuf.generator.ast.Definition readDefinition(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + de.haumacher.msgbuf.generator.ast.Definition result; in.beginArray(); String type = in.nextString(); switch (type) { @@ -185,14 +211,14 @@ public static Definition readDefinition(de.haumacher.msgbuf.json.JsonReader in) @Override protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { super.writeFields(out); - out.name(NAME); + out.name(NAME__PROP); out.value(getName()); } @Override protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { switch (field) { - case NAME: setName(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + case NAME__PROP: setName(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; default: super.readField(in, field); } } @@ -201,8 +227,8 @@ protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) t public abstract R visit(Visitor v, A arg); @Override - public final R visit(DefinitionBase.Visitor v, A arg) { - return visit((Definition.Visitor) v, arg); + public final R visit(de.haumacher.msgbuf.generator.ast.DefinitionBase.Visitor v, A arg) { + return visit((de.haumacher.msgbuf.generator.ast.Definition.Visitor) v, arg); } } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/DefinitionBase.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/DefinitionBase.java index dccfdd8b..a94b9b6f 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/DefinitionBase.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/DefinitionBase.java @@ -3,17 +3,17 @@ /** * Base class for type and field definitions. */ -public abstract class DefinitionBase extends WithOptions { +public abstract class DefinitionBase extends de.haumacher.msgbuf.generator.ast.WithOptions { - /** Visitor interface for the {@link DefinitionBase} hierarchy.*/ - public interface Visitor extends Part.Visitor, Definition.Visitor { + /** Visitor interface for the {@link de.haumacher.msgbuf.generator.ast.DefinitionBase} hierarchy.*/ + public interface Visitor extends de.haumacher.msgbuf.generator.ast.Part.Visitor, de.haumacher.msgbuf.generator.ast.Definition.Visitor { // Pure sum interface. } /** @see #getComment() */ - public static final String COMMENT = "comment"; + public static final String COMMENT__PROP = "comment"; private String _comment = ""; @@ -34,42 +34,65 @@ public final String getComment() { /** * @see #getComment() */ - public DefinitionBase setComment(String value) { + public de.haumacher.msgbuf.generator.ast.DefinitionBase setComment(String value) { internalSetComment(value); return this; } /** Internal setter for {@link #getComment()} without chain call utility. */ protected final void internalSetComment(String value) { - _listener.beforeSet(this, COMMENT, value); + _listener.beforeSet(this, COMMENT__PROP, value); _comment = value; + _listener.afterChanged(this, COMMENT__PROP); } @Override - public DefinitionBase setOptions(java.util.Map value) { + public de.haumacher.msgbuf.generator.ast.DefinitionBase setOptions(java.util.Map value) { internalSetOptions(value); return this; } @Override - public DefinitionBase putOption(String key, Option value) { + public de.haumacher.msgbuf.generator.ast.DefinitionBase putOption(String key, de.haumacher.msgbuf.generator.ast.Option value) { internalPutOption(key, value); return this; } - private static java.util.List PROPERTIES = java.util.Collections.unmodifiableList( - java.util.Arrays.asList( - COMMENT)); + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + COMMENT__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(de.haumacher.msgbuf.generator.ast.WithOptions.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(de.haumacher.msgbuf.generator.ast.WithOptions.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } @Override public java.util.List properties() { return PROPERTIES; } + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + @Override public Object get(String field) { switch (field) { - case COMMENT: return getComment(); + case COMMENT__PROP: return getComment(); default: return super.get(field); } } @@ -77,14 +100,14 @@ public Object get(String field) { @Override public void set(String field, Object value) { switch (field) { - case COMMENT: internalSetComment((String) value); break; + case COMMENT__PROP: internalSetComment((String) value); break; default: super.set(field, value); break; } } /** Reads a new instance from the given reader. */ - public static DefinitionBase readDefinitionBase(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { - DefinitionBase result; + public static de.haumacher.msgbuf.generator.ast.DefinitionBase readDefinitionBase(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + de.haumacher.msgbuf.generator.ast.DefinitionBase result; in.beginArray(); String type = in.nextString(); switch (type) { @@ -101,14 +124,14 @@ public static DefinitionBase readDefinitionBase(de.haumacher.msgbuf.json.JsonRea @Override protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { super.writeFields(out); - out.name(COMMENT); + out.name(COMMENT__PROP); out.value(getComment()); } @Override protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { switch (field) { - case COMMENT: setComment(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + case COMMENT__PROP: setComment(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; default: super.readField(in, field); } } @@ -117,8 +140,8 @@ protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) t public abstract R visit(Visitor v, A arg); @Override - public final R visit(WithOptions.Visitor v, A arg) { - return visit((DefinitionBase.Visitor) v, arg); + public final R visit(de.haumacher.msgbuf.generator.ast.WithOptions.Visitor v, A arg) { + return visit((de.haumacher.msgbuf.generator.ast.DefinitionBase.Visitor) v, arg); } } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/DefinitionFile.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/DefinitionFile.java index 7c665f9f..7e65b900 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/DefinitionFile.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/DefinitionFile.java @@ -5,42 +5,72 @@ * * @see #getDefinitions() */ -public class DefinitionFile extends WithOptions { +public class DefinitionFile extends de.haumacher.msgbuf.generator.ast.WithOptions { /** - * Creates a {@link DefinitionFile} instance. + * Creates a {@link de.haumacher.msgbuf.generator.ast.DefinitionFile} instance. */ - public static DefinitionFile create() { + public static de.haumacher.msgbuf.generator.ast.DefinitionFile create() { return new de.haumacher.msgbuf.generator.ast.DefinitionFile(); } - /** Identifier for the {@link DefinitionFile} type in JSON format. */ + /** Identifier for the {@link de.haumacher.msgbuf.generator.ast.DefinitionFile} type in JSON format. */ public static final String DEFINITION_FILE__TYPE = "DefinitionFile"; + /** @see #getComment() */ + public static final String COMMENT__PROP = "comment"; + /** @see #getPackage() */ - public static final String PACKAGE = "package"; + public static final String PACKAGE__PROP = "package"; + + /** @see #getImports() */ + public static final String IMPORTS__PROP = "imports"; /** @see #getDefinitions() */ - public static final String DEFINITIONS = "definitions"; + public static final String DEFINITIONS__PROP = "definitions"; + + private String _comment = ""; + + private de.haumacher.msgbuf.generator.ast.QName _package = null; - private QName _package = null; + private final java.util.List _imports = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, String element) { + _listener.beforeAdd(DefinitionFile.this, IMPORTS__PROP, index, element); + } + + @Override + protected void afterRemove(int index, String element) { + _listener.afterRemove(DefinitionFile.this, IMPORTS__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(DefinitionFile.this, IMPORTS__PROP); + } + }; + + private final java.util.List _definitions = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, de.haumacher.msgbuf.generator.ast.Definition element) { + _listener.beforeAdd(DefinitionFile.this, DEFINITIONS__PROP, index, element); + } - private final java.util.List _definitions = new de.haumacher.msgbuf.util.ReferenceList() { @Override - protected void beforeAdd(int index, Definition element) { - _listener.beforeAdd(DefinitionFile.this, DEFINITIONS, index, element); + protected void afterRemove(int index, de.haumacher.msgbuf.generator.ast.Definition element) { + _listener.afterRemove(DefinitionFile.this, DEFINITIONS__PROP, index, element); } @Override - protected void afterRemove(int index, Definition element) { - _listener.afterRemove(DefinitionFile.this, DEFINITIONS, index, element); + protected void afterChanged() { + _listener.afterChanged(DefinitionFile.this, DEFINITIONS__PROP); } }; /** * Creates a {@link DefinitionFile} instance. * - * @see DefinitionFile#create() + * @see de.haumacher.msgbuf.generator.ast.DefinitionFile#create() */ protected DefinitionFile() { super(); @@ -51,25 +81,48 @@ public TypeKind kind() { return TypeKind.DEFINITION_FILE; } + /** + * The documentation comment of the file (the doc comment before the syntax or package declaration). + */ + public final String getComment() { + return _comment; + } + + /** + * @see #getComment() + */ + public de.haumacher.msgbuf.generator.ast.DefinitionFile setComment(String value) { + internalSetComment(value); + return this; + } + + /** Internal setter for {@link #getComment()} without chain call utility. */ + protected final void internalSetComment(String value) { + _listener.beforeSet(this, COMMENT__PROP, value); + _comment = value; + _listener.afterChanged(this, COMMENT__PROP); + } + /** * The package name for all types in this file. */ - public final QName getPackage() { + public final de.haumacher.msgbuf.generator.ast.QName getPackage() { return _package; } /** * @see #getPackage() */ - public DefinitionFile setPackage(QName value) { + public de.haumacher.msgbuf.generator.ast.DefinitionFile setPackage(de.haumacher.msgbuf.generator.ast.QName value) { internalSetPackage(value); return this; } /** Internal setter for {@link #getPackage()} without chain call utility. */ - protected final void internalSetPackage(QName value) { - _listener.beforeSet(this, PACKAGE, value); + protected final void internalSetPackage(de.haumacher.msgbuf.generator.ast.QName value) { + _listener.beforeSet(this, PACKAGE__PROP, value); _package = value; + _listener.afterChanged(this, PACKAGE__PROP); } /** @@ -79,23 +132,64 @@ public final boolean hasPackage() { return _package != null; } + /** + * Import paths referencing other .proto files. + */ + public final java.util.List getImports() { + return _imports; + } + + /** + * @see #getImports() + */ + public de.haumacher.msgbuf.generator.ast.DefinitionFile setImports(java.util.List value) { + internalSetImports(value); + return this; + } + + /** Internal setter for {@link #getImports()} without chain call utility. */ + protected final void internalSetImports(java.util.List value) { + _imports.clear(); + _imports.addAll(value); + } + + /** + * Adds a value to the {@link #getImports()} list. + */ + public de.haumacher.msgbuf.generator.ast.DefinitionFile addImport(String value) { + internalAddImport(value); + return this; + } + + /** Implementation of {@link #addImport(String)} without chain call utility. */ + protected final void internalAddImport(String value) { + _imports.add(value); + } + + /** + * Removes a value from the {@link #getImports()} list. + */ + public final void removeImport(String value) { + _imports.remove(value); + } + /** * All definitions in this file. */ - public final java.util.List getDefinitions() { + public final java.util.List getDefinitions() { return _definitions; } /** * @see #getDefinitions() */ - public DefinitionFile setDefinitions(java.util.List value) { + public de.haumacher.msgbuf.generator.ast.DefinitionFile setDefinitions(java.util.List value) { internalSetDefinitions(value); return this; } /** Internal setter for {@link #getDefinitions()} without chain call utility. */ - protected final void internalSetDefinitions(java.util.List value) { + protected final void internalSetDefinitions(java.util.List value) { if (value == null) throw new IllegalArgumentException("Property 'definitions' cannot be null."); _definitions.clear(); _definitions.addAll(value); @@ -104,31 +198,31 @@ protected final void internalSetDefinitions(java.util.List /** * Adds a value to the {@link #getDefinitions()} list. */ - public DefinitionFile addDefinition(Definition value) { + public de.haumacher.msgbuf.generator.ast.DefinitionFile addDefinition(de.haumacher.msgbuf.generator.ast.Definition value) { internalAddDefinition(value); return this; } - /** Implementation of {@link #addDefinition(Definition)} without chain call utility. */ - protected final void internalAddDefinition(Definition value) { + /** Implementation of {@link #addDefinition(de.haumacher.msgbuf.generator.ast.Definition)} without chain call utility. */ + protected final void internalAddDefinition(de.haumacher.msgbuf.generator.ast.Definition value) { _definitions.add(value); } /** * Removes a value from the {@link #getDefinitions()} list. */ - public final void removeDefinition(Definition value) { + public final void removeDefinition(de.haumacher.msgbuf.generator.ast.Definition value) { _definitions.remove(value); } @Override - public DefinitionFile setOptions(java.util.Map value) { + public de.haumacher.msgbuf.generator.ast.DefinitionFile setOptions(java.util.Map value) { internalSetOptions(value); return this; } @Override - public DefinitionFile putOption(String key, Option value) { + public de.haumacher.msgbuf.generator.ast.DefinitionFile putOption(String key, de.haumacher.msgbuf.generator.ast.Option value) { internalPutOption(key, value); return this; } @@ -138,21 +232,47 @@ public String jsonType() { return DEFINITION_FILE__TYPE; } - private static java.util.List PROPERTIES = java.util.Collections.unmodifiableList( - java.util.Arrays.asList( - PACKAGE, - DEFINITIONS)); + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + COMMENT__PROP, + PACKAGE__PROP, + IMPORTS__PROP, + DEFINITIONS__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(de.haumacher.msgbuf.generator.ast.WithOptions.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(de.haumacher.msgbuf.generator.ast.WithOptions.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } @Override public java.util.List properties() { return PROPERTIES; } + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + @Override public Object get(String field) { switch (field) { - case PACKAGE: return getPackage(); - case DEFINITIONS: return getDefinitions(); + case COMMENT__PROP: return getComment(); + case PACKAGE__PROP: return getPackage(); + case IMPORTS__PROP: return getImports(); + case DEFINITIONS__PROP: return getDefinitions(); default: return super.get(field); } } @@ -160,14 +280,16 @@ public Object get(String field) { @Override public void set(String field, Object value) { switch (field) { - case PACKAGE: internalSetPackage((QName) value); break; - case DEFINITIONS: internalSetDefinitions(de.haumacher.msgbuf.util.Conversions.asList(Definition.class, value)); break; + case COMMENT__PROP: internalSetComment((String) value); break; + case PACKAGE__PROP: internalSetPackage((de.haumacher.msgbuf.generator.ast.QName) value); break; + case IMPORTS__PROP: internalSetImports(de.haumacher.msgbuf.util.Conversions.asList(String.class, value)); break; + case DEFINITIONS__PROP: internalSetDefinitions(de.haumacher.msgbuf.util.Conversions.asList(de.haumacher.msgbuf.generator.ast.Definition.class, value)); break; default: super.set(field, value); break; } } /** Reads a new instance from the given reader. */ - public static DefinitionFile readDefinitionFile(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + public static de.haumacher.msgbuf.generator.ast.DefinitionFile readDefinitionFile(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { de.haumacher.msgbuf.generator.ast.DefinitionFile result = new de.haumacher.msgbuf.generator.ast.DefinitionFile(); result.readContent(in); return result; @@ -176,13 +298,21 @@ public static DefinitionFile readDefinitionFile(de.haumacher.msgbuf.json.JsonRea @Override protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { super.writeFields(out); + out.name(COMMENT__PROP); + out.value(getComment()); if (hasPackage()) { - out.name(PACKAGE); + out.name(PACKAGE__PROP); getPackage().writeTo(out); } - out.name(DEFINITIONS); + out.name(IMPORTS__PROP); + out.beginArray(); + for (String x : getImports()) { + out.value(x); + } + out.endArray(); + out.name(DEFINITIONS__PROP); out.beginArray(); - for (Definition x : getDefinitions()) { + for (de.haumacher.msgbuf.generator.ast.Definition x : getDefinitions()) { x.writeTo(out); } out.endArray(); @@ -191,13 +321,26 @@ protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java. @Override protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { switch (field) { - case PACKAGE: setPackage(de.haumacher.msgbuf.generator.ast.QName.readQName(in)); break; - case DEFINITIONS: { + case COMMENT__PROP: setComment(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + case PACKAGE__PROP: setPackage(de.haumacher.msgbuf.generator.ast.QName.readQName(in)); break; + case IMPORTS__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); + } + in.endArray(); + setImports(newValue); + } + break; + case DEFINITIONS__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); in.beginArray(); while (in.hasNext()) { - addDefinition(de.haumacher.msgbuf.generator.ast.Definition.readDefinition(in)); + newValue.add(de.haumacher.msgbuf.generator.ast.Definition.readDefinition(in)); } in.endArray(); + setDefinitions(newValue); } break; default: super.readField(in, field); @@ -205,7 +348,7 @@ protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) t } @Override - public R visit(WithOptions.Visitor v, A arg) { + public R visit(de.haumacher.msgbuf.generator.ast.WithOptions.Visitor v, A arg) { return v.visit(this, arg); } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/EnumDef.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/EnumDef.java index 5b8fef18..23eca799 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/EnumDef.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/EnumDef.java @@ -3,37 +3,42 @@ /** * {@link Definition} of an enumeration. */ -public class EnumDef extends Definition { +public class EnumDef extends de.haumacher.msgbuf.generator.ast.Definition { /** - * Creates a {@link EnumDef} instance. + * Creates a {@link de.haumacher.msgbuf.generator.ast.EnumDef} instance. */ - public static EnumDef create() { + public static de.haumacher.msgbuf.generator.ast.EnumDef create() { return new de.haumacher.msgbuf.generator.ast.EnumDef(); } - /** Identifier for the {@link EnumDef} type in JSON format. */ + /** Identifier for the {@link de.haumacher.msgbuf.generator.ast.EnumDef} type in JSON format. */ public static final String ENUM_DEF__TYPE = "EnumDef"; /** @see #getConstants() */ - public static final String CONSTANTS = "constants"; + public static final String CONSTANTS__PROP = "constants"; - private final java.util.List _constants = new de.haumacher.msgbuf.util.ReferenceList() { + private final java.util.List _constants = new de.haumacher.msgbuf.util.ReferenceList() { @Override - protected void beforeAdd(int index, Constant element) { - _listener.beforeAdd(EnumDef.this, CONSTANTS, index, element); + protected void beforeAdd(int index, de.haumacher.msgbuf.generator.ast.Constant element) { + _listener.beforeAdd(EnumDef.this, CONSTANTS__PROP, index, element); } @Override - protected void afterRemove(int index, Constant element) { - _listener.afterRemove(EnumDef.this, CONSTANTS, index, element); + protected void afterRemove(int index, de.haumacher.msgbuf.generator.ast.Constant element) { + _listener.afterRemove(EnumDef.this, CONSTANTS__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(EnumDef.this, CONSTANTS__PROP); } }; /** * Creates a {@link EnumDef} instance. * - * @see EnumDef#create() + * @see de.haumacher.msgbuf.generator.ast.EnumDef#create() */ protected EnumDef() { super(); @@ -47,20 +52,20 @@ public TypeKind kind() { /** * All enum constants of this enumeration */ - public final java.util.List getConstants() { + public final java.util.List getConstants() { return _constants; } /** * @see #getConstants() */ - public EnumDef setConstants(java.util.List value) { + public de.haumacher.msgbuf.generator.ast.EnumDef setConstants(java.util.List value) { internalSetConstants(value); return this; } /** Internal setter for {@link #getConstants()} without chain call utility. */ - protected final void internalSetConstants(java.util.List value) { + protected final void internalSetConstants(java.util.List value) { if (value == null) throw new IllegalArgumentException("Property 'constants' cannot be null."); _constants.clear(); _constants.addAll(value); @@ -69,55 +74,55 @@ protected final void internalSetConstants(java.util.List val /** * Adds a value to the {@link #getConstants()} list. */ - public EnumDef addConstant(Constant value) { + public de.haumacher.msgbuf.generator.ast.EnumDef addConstant(de.haumacher.msgbuf.generator.ast.Constant value) { internalAddConstant(value); return this; } - /** Implementation of {@link #addConstant(Constant)} without chain call utility. */ - protected final void internalAddConstant(Constant value) { + /** Implementation of {@link #addConstant(de.haumacher.msgbuf.generator.ast.Constant)} without chain call utility. */ + protected final void internalAddConstant(de.haumacher.msgbuf.generator.ast.Constant value) { _constants.add(value); } /** * Removes a value from the {@link #getConstants()} list. */ - public final void removeConstant(Constant value) { + public final void removeConstant(de.haumacher.msgbuf.generator.ast.Constant value) { _constants.remove(value); } @Override - public EnumDef setName(String value) { + public de.haumacher.msgbuf.generator.ast.EnumDef setName(String value) { internalSetName(value); return this; } @Override - public EnumDef setFile(DefinitionFile value) { + public de.haumacher.msgbuf.generator.ast.EnumDef setFile(de.haumacher.msgbuf.generator.ast.DefinitionFile value) { internalSetFile(value); return this; } @Override - public EnumDef setOuter(MessageDef value) { + public de.haumacher.msgbuf.generator.ast.EnumDef setOuter(de.haumacher.msgbuf.generator.ast.MessageDef value) { internalSetOuter(value); return this; } @Override - public EnumDef setComment(String value) { + public de.haumacher.msgbuf.generator.ast.EnumDef setComment(String value) { internalSetComment(value); return this; } @Override - public EnumDef setOptions(java.util.Map value) { + public de.haumacher.msgbuf.generator.ast.EnumDef setOptions(java.util.Map value) { internalSetOptions(value); return this; } @Override - public EnumDef putOption(String key, Option value) { + public de.haumacher.msgbuf.generator.ast.EnumDef putOption(String key, de.haumacher.msgbuf.generator.ast.Option value) { internalPutOption(key, value); return this; } @@ -127,19 +132,41 @@ public String jsonType() { return ENUM_DEF__TYPE; } - private static java.util.List PROPERTIES = java.util.Collections.unmodifiableList( - java.util.Arrays.asList( - CONSTANTS)); + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + CONSTANTS__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(de.haumacher.msgbuf.generator.ast.Definition.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(de.haumacher.msgbuf.generator.ast.Definition.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } @Override public java.util.List properties() { return PROPERTIES; } + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + @Override public Object get(String field) { switch (field) { - case CONSTANTS: return getConstants(); + case CONSTANTS__PROP: return getConstants(); default: return super.get(field); } } @@ -147,13 +174,13 @@ public Object get(String field) { @Override public void set(String field, Object value) { switch (field) { - case CONSTANTS: internalSetConstants(de.haumacher.msgbuf.util.Conversions.asList(Constant.class, value)); break; + case CONSTANTS__PROP: internalSetConstants(de.haumacher.msgbuf.util.Conversions.asList(de.haumacher.msgbuf.generator.ast.Constant.class, value)); break; default: super.set(field, value); break; } } /** Reads a new instance from the given reader. */ - public static EnumDef readEnumDef(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + public static de.haumacher.msgbuf.generator.ast.EnumDef readEnumDef(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { de.haumacher.msgbuf.generator.ast.EnumDef result = new de.haumacher.msgbuf.generator.ast.EnumDef(); result.readContent(in); return result; @@ -162,9 +189,9 @@ public static EnumDef readEnumDef(de.haumacher.msgbuf.json.JsonReader in) throws @Override protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { super.writeFields(out); - out.name(CONSTANTS); + out.name(CONSTANTS__PROP); out.beginArray(); - for (Constant x : getConstants()) { + for (de.haumacher.msgbuf.generator.ast.Constant x : getConstants()) { x.writeContent(out); } out.endArray(); @@ -173,12 +200,14 @@ protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java. @Override protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { switch (field) { - case CONSTANTS: { + case CONSTANTS__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); in.beginArray(); while (in.hasNext()) { - addConstant(de.haumacher.msgbuf.generator.ast.Constant.readConstant(in)); + newValue.add(de.haumacher.msgbuf.generator.ast.Constant.readConstant(in)); } in.endArray(); + setConstants(newValue); } break; default: super.readField(in, field); @@ -186,7 +215,7 @@ protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) t } @Override - public R visit(Definition.Visitor v, A arg) { + public R visit(de.haumacher.msgbuf.generator.ast.Definition.Visitor v, A arg) { return v.visit(this, arg); } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Field.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Field.java index 1a57a7e6..c8e42003 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Field.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Field.java @@ -3,37 +3,42 @@ /** * A field definition of a {@link MessageDef}. */ -public class Field extends Part implements de.haumacher.msgbuf.generator.FieldOperations { +public class Field extends de.haumacher.msgbuf.generator.ast.Part implements de.haumacher.msgbuf.generator.FieldOperations { /** - * Creates a {@link Field} instance. + * Creates a {@link de.haumacher.msgbuf.generator.ast.Field} instance. */ - public static Field create() { + public static de.haumacher.msgbuf.generator.ast.Field create() { return new de.haumacher.msgbuf.generator.ast.Field(); } - /** Identifier for the {@link Field} type in JSON format. */ + /** Identifier for the {@link de.haumacher.msgbuf.generator.ast.Field} type in JSON format. */ public static final String FIELD__TYPE = "Field"; /** @see #isTransient() */ - public static final String TRANSIENT = "transient"; + public static final String TRANSIENT__PROP = "transient"; /** @see #isRepeated() */ - public static final String REPEATED = "repeated"; + public static final String REPEATED__PROP = "repeated"; /** @see #getType() */ - public static final String TYPE = "type"; + public static final String TYPE__PROP = "type"; + + /** @see #getDefaultValue() */ + public static final String DEFAULT_VALUE__PROP = "defaultValue"; private boolean _transient = false; private boolean _repeated = false; - private Type _type = null; + private de.haumacher.msgbuf.generator.ast.Type _type = null; + + private String _defaultValue = null; /** * Creates a {@link Field} instance. * - * @see Field#create() + * @see de.haumacher.msgbuf.generator.ast.Field#create() */ protected Field() { super(); @@ -54,15 +59,16 @@ public final boolean isTransient() { /** * @see #isTransient() */ - public Field setTransient(boolean value) { + public de.haumacher.msgbuf.generator.ast.Field setTransient(boolean value) { internalSetTransient(value); return this; } /** Internal setter for {@link #isTransient()} without chain call utility. */ protected final void internalSetTransient(boolean value) { - _listener.beforeSet(this, TRANSIENT, value); + _listener.beforeSet(this, TRANSIENT__PROP, value); _transient = value; + _listener.afterChanged(this, TRANSIENT__PROP); } /** @@ -75,36 +81,38 @@ public final boolean isRepeated() { /** * @see #isRepeated() */ - public Field setRepeated(boolean value) { + public de.haumacher.msgbuf.generator.ast.Field setRepeated(boolean value) { internalSetRepeated(value); return this; } /** Internal setter for {@link #isRepeated()} without chain call utility. */ protected final void internalSetRepeated(boolean value) { - _listener.beforeSet(this, REPEATED, value); + _listener.beforeSet(this, REPEATED__PROP, value); _repeated = value; + _listener.afterChanged(this, REPEATED__PROP); } /** * The type of values that can be stored in this field. */ - public final Type getType() { + public final de.haumacher.msgbuf.generator.ast.Type getType() { return _type; } /** * @see #getType() */ - public Field setType(Type value) { + public de.haumacher.msgbuf.generator.ast.Field setType(de.haumacher.msgbuf.generator.ast.Type value) { internalSetType(value); return this; } /** Internal setter for {@link #getType()} without chain call utility. */ - protected final void internalSetType(Type value) { - _listener.beforeSet(this, TYPE, value); + protected final void internalSetType(de.haumacher.msgbuf.generator.ast.Type value) { + _listener.beforeSet(this, TYPE__PROP, value); _type = value; + _listener.afterChanged(this, TYPE__PROP); } /** @@ -114,38 +122,67 @@ public final boolean hasType() { return _type != null; } + /** + * The initializer value to assign to the field. + */ + public final String getDefaultValue() { + return _defaultValue; + } + + /** + * @see #getDefaultValue() + */ + public de.haumacher.msgbuf.generator.ast.Field setDefaultValue(String value) { + internalSetDefaultValue(value); + return this; + } + + /** Internal setter for {@link #getDefaultValue()} without chain call utility. */ + protected final void internalSetDefaultValue(String value) { + _listener.beforeSet(this, DEFAULT_VALUE__PROP, value); + _defaultValue = value; + _listener.afterChanged(this, DEFAULT_VALUE__PROP); + } + + /** + * Checks, whether {@link #getDefaultValue()} has a value. + */ + public final boolean hasDefaultValue() { + return _defaultValue != null; + } + @Override - public Field setName(String value) { + public de.haumacher.msgbuf.generator.ast.Field setName(String value) { internalSetName(value); return this; } @Override - public Field setIndex(int value) { + public de.haumacher.msgbuf.generator.ast.Field setIndex(int value) { internalSetIndex(value); return this; } @Override - public Field setOwner(Definition value) { + public de.haumacher.msgbuf.generator.ast.Field setOwner(de.haumacher.msgbuf.generator.ast.Definition value) { internalSetOwner(value); return this; } @Override - public Field setComment(String value) { + public de.haumacher.msgbuf.generator.ast.Field setComment(String value) { internalSetComment(value); return this; } @Override - public Field setOptions(java.util.Map value) { + public de.haumacher.msgbuf.generator.ast.Field setOptions(java.util.Map value) { internalSetOptions(value); return this; } @Override - public Field putOption(String key, Option value) { + public de.haumacher.msgbuf.generator.ast.Field putOption(String key, de.haumacher.msgbuf.generator.ast.Option value) { internalPutOption(key, value); return this; } @@ -155,23 +192,47 @@ public String jsonType() { return FIELD__TYPE; } - private static java.util.List PROPERTIES = java.util.Collections.unmodifiableList( - java.util.Arrays.asList( - TRANSIENT, - REPEATED, - TYPE)); + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + TRANSIENT__PROP, + REPEATED__PROP, + TYPE__PROP, + DEFAULT_VALUE__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(de.haumacher.msgbuf.generator.ast.Part.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(de.haumacher.msgbuf.generator.ast.Part.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } @Override public java.util.List properties() { return PROPERTIES; } + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + @Override public Object get(String field) { switch (field) { - case TRANSIENT: return isTransient(); - case REPEATED: return isRepeated(); - case TYPE: return getType(); + case TRANSIENT__PROP: return isTransient(); + case REPEATED__PROP: return isRepeated(); + case TYPE__PROP: return getType(); + case DEFAULT_VALUE__PROP: return getDefaultValue(); default: return super.get(field); } } @@ -179,15 +240,16 @@ public Object get(String field) { @Override public void set(String field, Object value) { switch (field) { - case TRANSIENT: internalSetTransient((boolean) value); break; - case REPEATED: internalSetRepeated((boolean) value); break; - case TYPE: internalSetType((Type) value); break; + case TRANSIENT__PROP: internalSetTransient((boolean) value); break; + case REPEATED__PROP: internalSetRepeated((boolean) value); break; + case TYPE__PROP: internalSetType((de.haumacher.msgbuf.generator.ast.Type) value); break; + case DEFAULT_VALUE__PROP: internalSetDefaultValue((String) value); break; default: super.set(field, value); break; } } /** Reads a new instance from the given reader. */ - public static Field readField(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + public static de.haumacher.msgbuf.generator.ast.Field readField(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { de.haumacher.msgbuf.generator.ast.Field result = new de.haumacher.msgbuf.generator.ast.Field(); result.readContent(in); return result; @@ -196,28 +258,38 @@ public static Field readField(de.haumacher.msgbuf.json.JsonReader in) throws jav @Override protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { super.writeFields(out); - out.name(TRANSIENT); + out.name(TRANSIENT__PROP); out.value(isTransient()); - out.name(REPEATED); + out.name(REPEATED__PROP); out.value(isRepeated()); if (hasType()) { - out.name(TYPE); + out.name(TYPE__PROP); getType().writeTo(out); } + if (hasDefaultValue()) { + out.name(DEFAULT_VALUE__PROP); + out.value(getDefaultValue()); + } } @Override protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { switch (field) { - case TRANSIENT: setTransient(in.nextBoolean()); break; - case REPEATED: setRepeated(in.nextBoolean()); break; - case TYPE: setType(de.haumacher.msgbuf.generator.ast.Type.readType(in)); break; + case TRANSIENT__PROP: setTransient(in.nextBoolean()); break; + case REPEATED__PROP: setRepeated(in.nextBoolean()); break; + case TYPE__PROP: setType(de.haumacher.msgbuf.generator.ast.Type.readType(in)); break; + case DEFAULT_VALUE__PROP: setDefaultValue(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; default: super.readField(in, field); } } @Override - public R visit(Part.Visitor v, A arg) { + public Field self() { + return this; + } + + @Override + public R visit(de.haumacher.msgbuf.generator.ast.Part.Visitor v, A arg) { return v.visit(this, arg); } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Flag.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Flag.java index c80cfbec..a53910a8 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Flag.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Flag.java @@ -3,27 +3,27 @@ /** * {@link Option} annotating a boolean value */ -public class Flag extends Option { +public class Flag extends de.haumacher.msgbuf.generator.ast.Option { /** - * Creates a {@link Flag} instance. + * Creates a {@link de.haumacher.msgbuf.generator.ast.Flag} instance. */ - public static Flag create() { + public static de.haumacher.msgbuf.generator.ast.Flag create() { return new de.haumacher.msgbuf.generator.ast.Flag(); } - /** Identifier for the {@link Flag} type in JSON format. */ + /** Identifier for the {@link de.haumacher.msgbuf.generator.ast.Flag} type in JSON format. */ public static final String FLAG__TYPE = "Flag"; /** @see #isValue() */ - public static final String VALUE = "value"; + public static final String VALUE__PROP = "value"; private boolean _value = false; /** * Creates a {@link Flag} instance. * - * @see Flag#create() + * @see de.haumacher.msgbuf.generator.ast.Flag#create() */ protected Flag() { super(); @@ -44,15 +44,16 @@ public final boolean isValue() { /** * @see #isValue() */ - public Flag setValue(boolean value) { + public de.haumacher.msgbuf.generator.ast.Flag setValue(boolean value) { internalSetValue(value); return this; } /** Internal setter for {@link #isValue()} without chain call utility. */ protected final void internalSetValue(boolean value) { - _listener.beforeSet(this, VALUE, value); + _listener.beforeSet(this, VALUE__PROP, value); _value = value; + _listener.afterChanged(this, VALUE__PROP); } @Override @@ -60,19 +61,35 @@ public String jsonType() { return FLAG__TYPE; } - private static java.util.List PROPERTIES = java.util.Collections.unmodifiableList( - java.util.Arrays.asList( - VALUE)); + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + VALUE__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } @Override public java.util.List properties() { return PROPERTIES; } + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + @Override public Object get(String field) { switch (field) { - case VALUE: return isValue(); + case VALUE__PROP: return isValue(); default: return super.get(field); } } @@ -80,13 +97,13 @@ public Object get(String field) { @Override public void set(String field, Object value) { switch (field) { - case VALUE: internalSetValue((boolean) value); break; + case VALUE__PROP: internalSetValue((boolean) value); break; default: super.set(field, value); break; } } /** Reads a new instance from the given reader. */ - public static Flag readFlag(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + public static de.haumacher.msgbuf.generator.ast.Flag readFlag(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { de.haumacher.msgbuf.generator.ast.Flag result = new de.haumacher.msgbuf.generator.ast.Flag(); result.readContent(in); return result; @@ -95,20 +112,20 @@ public static Flag readFlag(de.haumacher.msgbuf.json.JsonReader in) throws java. @Override protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { super.writeFields(out); - out.name(VALUE); + out.name(VALUE__PROP); out.value(isValue()); } @Override protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { switch (field) { - case VALUE: setValue(in.nextBoolean()); break; + case VALUE__PROP: setValue(in.nextBoolean()); break; default: super.readField(in, field); } } @Override - public R visit(Option.Visitor v, A arg) { + public R visit(de.haumacher.msgbuf.generator.ast.Option.Visitor v, A arg) { return v.visit(this, arg); } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/MapType.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/MapType.java index 288e200c..d50c1c43 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/MapType.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/MapType.java @@ -3,32 +3,32 @@ /** * A {@link Type} that is composed of a key and a value. */ -public class MapType extends Type { +public class MapType extends de.haumacher.msgbuf.generator.ast.Type { /** - * Creates a {@link MapType} instance. + * Creates a {@link de.haumacher.msgbuf.generator.ast.MapType} instance. */ - public static MapType create() { + public static de.haumacher.msgbuf.generator.ast.MapType create() { return new de.haumacher.msgbuf.generator.ast.MapType(); } - /** Identifier for the {@link MapType} type in JSON format. */ + /** Identifier for the {@link de.haumacher.msgbuf.generator.ast.MapType} type in JSON format. */ public static final String MAP_TYPE__TYPE = "MapType"; /** @see #getKeyType() */ - public static final String KEY_TYPE = "keyType"; + public static final String KEY_TYPE__PROP = "keyType"; /** @see #getValueType() */ - public static final String VALUE_TYPE = "valueType"; + public static final String VALUE_TYPE__PROP = "valueType"; - private Type _keyType = null; + private de.haumacher.msgbuf.generator.ast.Type _keyType = null; - private Type _valueType = null; + private de.haumacher.msgbuf.generator.ast.Type _valueType = null; /** * Creates a {@link MapType} instance. * - * @see MapType#create() + * @see de.haumacher.msgbuf.generator.ast.MapType#create() */ protected MapType() { super(); @@ -42,22 +42,23 @@ public TypeKind kind() { /** * The key type of this map. */ - public final Type getKeyType() { + public final de.haumacher.msgbuf.generator.ast.Type getKeyType() { return _keyType; } /** * @see #getKeyType() */ - public MapType setKeyType(Type value) { + public de.haumacher.msgbuf.generator.ast.MapType setKeyType(de.haumacher.msgbuf.generator.ast.Type value) { internalSetKeyType(value); return this; } /** Internal setter for {@link #getKeyType()} without chain call utility. */ - protected final void internalSetKeyType(Type value) { - _listener.beforeSet(this, KEY_TYPE, value); + protected final void internalSetKeyType(de.haumacher.msgbuf.generator.ast.Type value) { + _listener.beforeSet(this, KEY_TYPE__PROP, value); _keyType = value; + _listener.afterChanged(this, KEY_TYPE__PROP); } /** @@ -70,22 +71,23 @@ public final boolean hasKeyType() { /** * The value type of this map. */ - public final Type getValueType() { + public final de.haumacher.msgbuf.generator.ast.Type getValueType() { return _valueType; } /** * @see #getValueType() */ - public MapType setValueType(Type value) { + public de.haumacher.msgbuf.generator.ast.MapType setValueType(de.haumacher.msgbuf.generator.ast.Type value) { internalSetValueType(value); return this; } /** Internal setter for {@link #getValueType()} without chain call utility. */ - protected final void internalSetValueType(Type value) { - _listener.beforeSet(this, VALUE_TYPE, value); + protected final void internalSetValueType(de.haumacher.msgbuf.generator.ast.Type value) { + _listener.beforeSet(this, VALUE_TYPE__PROP, value); _valueType = value; + _listener.afterChanged(this, VALUE_TYPE__PROP); } /** @@ -100,21 +102,37 @@ public String jsonType() { return MAP_TYPE__TYPE; } - private static java.util.List PROPERTIES = java.util.Collections.unmodifiableList( - java.util.Arrays.asList( - KEY_TYPE, - VALUE_TYPE)); + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + KEY_TYPE__PROP, + VALUE_TYPE__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } @Override public java.util.List properties() { return PROPERTIES; } + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + @Override public Object get(String field) { switch (field) { - case KEY_TYPE: return getKeyType(); - case VALUE_TYPE: return getValueType(); + case KEY_TYPE__PROP: return getKeyType(); + case VALUE_TYPE__PROP: return getValueType(); default: return super.get(field); } } @@ -122,14 +140,14 @@ public Object get(String field) { @Override public void set(String field, Object value) { switch (field) { - case KEY_TYPE: internalSetKeyType((Type) value); break; - case VALUE_TYPE: internalSetValueType((Type) value); break; + case KEY_TYPE__PROP: internalSetKeyType((de.haumacher.msgbuf.generator.ast.Type) value); break; + case VALUE_TYPE__PROP: internalSetValueType((de.haumacher.msgbuf.generator.ast.Type) value); break; default: super.set(field, value); break; } } /** Reads a new instance from the given reader. */ - public static MapType readMapType(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + public static de.haumacher.msgbuf.generator.ast.MapType readMapType(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { de.haumacher.msgbuf.generator.ast.MapType result = new de.haumacher.msgbuf.generator.ast.MapType(); result.readContent(in); return result; @@ -139,11 +157,11 @@ public static MapType readMapType(de.haumacher.msgbuf.json.JsonReader in) throws protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { super.writeFields(out); if (hasKeyType()) { - out.name(KEY_TYPE); + out.name(KEY_TYPE__PROP); getKeyType().writeTo(out); } if (hasValueType()) { - out.name(VALUE_TYPE); + out.name(VALUE_TYPE__PROP); getValueType().writeTo(out); } } @@ -151,14 +169,14 @@ protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java. @Override protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { switch (field) { - case KEY_TYPE: setKeyType(de.haumacher.msgbuf.generator.ast.Type.readType(in)); break; - case VALUE_TYPE: setValueType(de.haumacher.msgbuf.generator.ast.Type.readType(in)); break; + case KEY_TYPE__PROP: setKeyType(de.haumacher.msgbuf.generator.ast.Type.readType(in)); break; + case VALUE_TYPE__PROP: setValueType(de.haumacher.msgbuf.generator.ast.Type.readType(in)); break; default: super.readField(in, field); } } @Override - public R visit(Type.Visitor v, A arg) { + public R visit(de.haumacher.msgbuf.generator.ast.Type.Visitor v, A arg) { return v.visit(this, arg); } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/MessageDef.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/MessageDef.java index 10ab7d37..7126942f 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/MessageDef.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/MessageDef.java @@ -3,87 +3,102 @@ /** * {@link Definition} of a data class. */ -public class MessageDef extends Definition { +public class MessageDef extends de.haumacher.msgbuf.generator.ast.Definition implements de.haumacher.msgbuf.generator.MessageDefOperations { /** - * Creates a {@link MessageDef} instance. + * Creates a {@link de.haumacher.msgbuf.generator.ast.MessageDef} instance. */ - public static MessageDef create() { + public static de.haumacher.msgbuf.generator.ast.MessageDef create() { return new de.haumacher.msgbuf.generator.ast.MessageDef(); } - /** Identifier for the {@link MessageDef} type in JSON format. */ + /** Identifier for the {@link de.haumacher.msgbuf.generator.ast.MessageDef} type in JSON format. */ public static final String MESSAGE_DEF__TYPE = "MessageDef"; /** @see #isAbstract() */ - public static final String ABSTRACT = "abstract"; + public static final String ABSTRACT__PROP = "abstract"; /** @see #getExtends() */ - public static final String EXTENDS = "extends"; + public static final String EXTENDS__PROP = "extends"; /** @see #getDefinitions() */ - public static final String DEFINITIONS = "definitions"; + public static final String DEFINITIONS__PROP = "definitions"; /** @see #getFields() */ - public static final String FIELDS = "fields"; + public static final String FIELDS__PROP = "fields"; /** @see #getSpecializations() */ - public static final String SPECIALIZATIONS = "specializations"; + public static final String SPECIALIZATIONS__PROP = "specializations"; /** @see #getExtendedDef() */ - public static final String EXTENDED_DEF = "extendedDef"; + public static final String EXTENDED_DEF__PROP = "extendedDef"; /** @see #getId() */ - public static final String ID = "id"; + public static final String ID__PROP = "id"; private boolean _abstract = false; - private QName _extends = null; + private de.haumacher.msgbuf.generator.ast.QName _extends = null; - private final java.util.List _definitions = new de.haumacher.msgbuf.util.ReferenceList() { + private final java.util.List _definitions = new de.haumacher.msgbuf.util.ReferenceList() { @Override - protected void beforeAdd(int index, Definition element) { - _listener.beforeAdd(MessageDef.this, DEFINITIONS, index, element); + protected void beforeAdd(int index, de.haumacher.msgbuf.generator.ast.Definition element) { + _listener.beforeAdd(MessageDef.this, DEFINITIONS__PROP, index, element); } @Override - protected void afterRemove(int index, Definition element) { - _listener.afterRemove(MessageDef.this, DEFINITIONS, index, element); + protected void afterRemove(int index, de.haumacher.msgbuf.generator.ast.Definition element) { + _listener.afterRemove(MessageDef.this, DEFINITIONS__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(MessageDef.this, DEFINITIONS__PROP); } }; - private final java.util.List _fields = new de.haumacher.msgbuf.util.ReferenceList() { + private final java.util.List _fields = new de.haumacher.msgbuf.util.ReferenceList() { @Override - protected void beforeAdd(int index, Field element) { - _listener.beforeAdd(MessageDef.this, FIELDS, index, element); + protected void beforeAdd(int index, de.haumacher.msgbuf.generator.ast.Field element) { + _listener.beforeAdd(MessageDef.this, FIELDS__PROP, index, element); } @Override - protected void afterRemove(int index, Field element) { - _listener.afterRemove(MessageDef.this, FIELDS, index, element); + protected void afterRemove(int index, de.haumacher.msgbuf.generator.ast.Field element) { + _listener.afterRemove(MessageDef.this, FIELDS__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(MessageDef.this, FIELDS__PROP); } }; - private transient final java.util.List _specializations = new de.haumacher.msgbuf.util.ReferenceList() { + private transient final java.util.List _specializations = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, de.haumacher.msgbuf.generator.ast.MessageDef element) { + _listener.beforeAdd(MessageDef.this, SPECIALIZATIONS__PROP, index, element); + } + @Override - protected void beforeAdd(int index, MessageDef element) { - _listener.beforeAdd(MessageDef.this, SPECIALIZATIONS, index, element); + protected void afterRemove(int index, de.haumacher.msgbuf.generator.ast.MessageDef element) { + _listener.afterRemove(MessageDef.this, SPECIALIZATIONS__PROP, index, element); } @Override - protected void afterRemove(int index, MessageDef element) { - _listener.afterRemove(MessageDef.this, SPECIALIZATIONS, index, element); + protected void afterChanged() { + _listener.afterChanged(MessageDef.this, SPECIALIZATIONS__PROP); } }; - private transient MessageDef _extendedDef = null; + private transient de.haumacher.msgbuf.generator.ast.MessageDef _extendedDef = null; private transient int _id = 0; /** * Creates a {@link MessageDef} instance. * - * @see MessageDef#create() + * @see de.haumacher.msgbuf.generator.ast.MessageDef#create() */ protected MessageDef() { super(); @@ -104,36 +119,38 @@ public final boolean isAbstract() { /** * @see #isAbstract() */ - public MessageDef setAbstract(boolean value) { + public de.haumacher.msgbuf.generator.ast.MessageDef setAbstract(boolean value) { internalSetAbstract(value); return this; } /** Internal setter for {@link #isAbstract()} without chain call utility. */ protected final void internalSetAbstract(boolean value) { - _listener.beforeSet(this, ABSTRACT, value); + _listener.beforeSet(this, ABSTRACT__PROP, value); _abstract = value; + _listener.afterChanged(this, ABSTRACT__PROP); } /** * Optional reference to another {@link MessageDef} whoes fields are inherited. */ - public final QName getExtends() { + public final de.haumacher.msgbuf.generator.ast.QName getExtends() { return _extends; } /** * @see #getExtends() */ - public MessageDef setExtends(QName value) { + public de.haumacher.msgbuf.generator.ast.MessageDef setExtends(de.haumacher.msgbuf.generator.ast.QName value) { internalSetExtends(value); return this; } /** Internal setter for {@link #getExtends()} without chain call utility. */ - protected final void internalSetExtends(QName value) { - _listener.beforeSet(this, EXTENDS, value); + protected final void internalSetExtends(de.haumacher.msgbuf.generator.ast.QName value) { + _listener.beforeSet(this, EXTENDS__PROP, value); _extends = value; + _listener.afterChanged(this, EXTENDS__PROP); } /** @@ -146,20 +163,20 @@ public final boolean hasExtends() { /** * Ohter {@link Definition}s that are local to this data class. */ - public final java.util.List getDefinitions() { + public final java.util.List getDefinitions() { return _definitions; } /** * @see #getDefinitions() */ - public MessageDef setDefinitions(java.util.List value) { + public de.haumacher.msgbuf.generator.ast.MessageDef setDefinitions(java.util.List value) { internalSetDefinitions(value); return this; } /** Internal setter for {@link #getDefinitions()} without chain call utility. */ - protected final void internalSetDefinitions(java.util.List value) { + protected final void internalSetDefinitions(java.util.List value) { if (value == null) throw new IllegalArgumentException("Property 'definitions' cannot be null."); _definitions.clear(); _definitions.addAll(value); @@ -168,20 +185,20 @@ protected final void internalSetDefinitions(java.util.List /** * Adds a value to the {@link #getDefinitions()} list. */ - public MessageDef addDefinition(Definition value) { + public de.haumacher.msgbuf.generator.ast.MessageDef addDefinition(de.haumacher.msgbuf.generator.ast.Definition value) { internalAddDefinition(value); return this; } - /** Implementation of {@link #addDefinition(Definition)} without chain call utility. */ - protected final void internalAddDefinition(Definition value) { + /** Implementation of {@link #addDefinition(de.haumacher.msgbuf.generator.ast.Definition)} without chain call utility. */ + protected final void internalAddDefinition(de.haumacher.msgbuf.generator.ast.Definition value) { _definitions.add(value); } /** * Removes a value from the {@link #getDefinitions()} list. */ - public final void removeDefinition(Definition value) { + public final void removeDefinition(de.haumacher.msgbuf.generator.ast.Definition value) { _definitions.remove(value); } @@ -194,20 +211,20 @@ public final void removeDefinition(Definition value) { * * @see #getExtends() */ - public final java.util.List getFields() { + public final java.util.List getFields() { return _fields; } /** * @see #getFields() */ - public MessageDef setFields(java.util.List value) { + public de.haumacher.msgbuf.generator.ast.MessageDef setFields(java.util.List value) { internalSetFields(value); return this; } /** Internal setter for {@link #getFields()} without chain call utility. */ - protected final void internalSetFields(java.util.List value) { + protected final void internalSetFields(java.util.List value) { if (value == null) throw new IllegalArgumentException("Property 'fields' cannot be null."); _fields.clear(); _fields.addAll(value); @@ -216,40 +233,40 @@ protected final void internalSetFields(java.util.List value) { /** * Adds a value to the {@link #getFields()} list. */ - public MessageDef addField(Field value) { + public de.haumacher.msgbuf.generator.ast.MessageDef addField(de.haumacher.msgbuf.generator.ast.Field value) { internalAddField(value); return this; } - /** Implementation of {@link #addField(Field)} without chain call utility. */ - protected final void internalAddField(Field value) { + /** Implementation of {@link #addField(de.haumacher.msgbuf.generator.ast.Field)} without chain call utility. */ + protected final void internalAddField(de.haumacher.msgbuf.generator.ast.Field value) { _fields.add(value); } /** * Removes a value from the {@link #getFields()} list. */ - public final void removeField(Field value) { + public final void removeField(de.haumacher.msgbuf.generator.ast.Field value) { _fields.remove(value); } /** * All {@link MessageDef data classes} that inherit from this data class. */ - public final java.util.List getSpecializations() { + public final java.util.List getSpecializations() { return _specializations; } /** * @see #getSpecializations() */ - public MessageDef setSpecializations(java.util.List value) { + public de.haumacher.msgbuf.generator.ast.MessageDef setSpecializations(java.util.List value) { internalSetSpecializations(value); return this; } /** Internal setter for {@link #getSpecializations()} without chain call utility. */ - protected final void internalSetSpecializations(java.util.List value) { + protected final void internalSetSpecializations(java.util.List value) { if (value == null) throw new IllegalArgumentException("Property 'specializations' cannot be null."); _specializations.clear(); _specializations.addAll(value); @@ -258,42 +275,43 @@ protected final void internalSetSpecializations(java.util.List value) { + public de.haumacher.msgbuf.generator.ast.MessageDef setOptions(java.util.Map value) { internalSetOptions(value); return this; } @Override - public MessageDef putOption(String key, Option value) { + public de.haumacher.msgbuf.generator.ast.MessageDef putOption(String key, de.haumacher.msgbuf.generator.ast.Option value) { internalPutOption(key, value); return this; } @@ -365,31 +384,55 @@ public String jsonType() { return MESSAGE_DEF__TYPE; } - private static java.util.List PROPERTIES = java.util.Collections.unmodifiableList( - java.util.Arrays.asList( - ABSTRACT, - EXTENDS, - DEFINITIONS, - FIELDS, - SPECIALIZATIONS, - EXTENDED_DEF, - ID)); + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + ABSTRACT__PROP, + EXTENDS__PROP, + DEFINITIONS__PROP, + FIELDS__PROP, + SPECIALIZATIONS__PROP, + EXTENDED_DEF__PROP, + ID__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(de.haumacher.msgbuf.generator.ast.Definition.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(de.haumacher.msgbuf.generator.ast.Definition.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + SPECIALIZATIONS__PROP, + EXTENDED_DEF__PROP, + ID__PROP)); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } @Override public java.util.List properties() { return PROPERTIES; } + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + @Override public Object get(String field) { switch (field) { - case ABSTRACT: return isAbstract(); - case EXTENDS: return getExtends(); - case DEFINITIONS: return getDefinitions(); - case FIELDS: return getFields(); - case SPECIALIZATIONS: return getSpecializations(); - case EXTENDED_DEF: return getExtendedDef(); - case ID: return getId(); + case ABSTRACT__PROP: return isAbstract(); + case EXTENDS__PROP: return getExtends(); + case DEFINITIONS__PROP: return getDefinitions(); + case FIELDS__PROP: return getFields(); + case SPECIALIZATIONS__PROP: return getSpecializations(); + case EXTENDED_DEF__PROP: return getExtendedDef(); + case ID__PROP: return getId(); default: return super.get(field); } } @@ -397,19 +440,19 @@ public Object get(String field) { @Override public void set(String field, Object value) { switch (field) { - case ABSTRACT: internalSetAbstract((boolean) value); break; - case EXTENDS: internalSetExtends((QName) value); break; - case DEFINITIONS: internalSetDefinitions(de.haumacher.msgbuf.util.Conversions.asList(Definition.class, value)); break; - case FIELDS: internalSetFields(de.haumacher.msgbuf.util.Conversions.asList(Field.class, value)); break; - case SPECIALIZATIONS: internalSetSpecializations(de.haumacher.msgbuf.util.Conversions.asList(MessageDef.class, value)); break; - case EXTENDED_DEF: internalSetExtendedDef((MessageDef) value); break; - case ID: internalSetId((int) value); break; + case ABSTRACT__PROP: internalSetAbstract((boolean) value); break; + case EXTENDS__PROP: internalSetExtends((de.haumacher.msgbuf.generator.ast.QName) value); break; + case DEFINITIONS__PROP: internalSetDefinitions(de.haumacher.msgbuf.util.Conversions.asList(de.haumacher.msgbuf.generator.ast.Definition.class, value)); break; + case FIELDS__PROP: internalSetFields(de.haumacher.msgbuf.util.Conversions.asList(de.haumacher.msgbuf.generator.ast.Field.class, value)); break; + case SPECIALIZATIONS__PROP: internalSetSpecializations(de.haumacher.msgbuf.util.Conversions.asList(de.haumacher.msgbuf.generator.ast.MessageDef.class, value)); break; + case EXTENDED_DEF__PROP: internalSetExtendedDef((de.haumacher.msgbuf.generator.ast.MessageDef) value); break; + case ID__PROP: internalSetId((int) value); break; default: super.set(field, value); break; } } /** Reads a new instance from the given reader. */ - public static MessageDef readMessageDef(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + public static de.haumacher.msgbuf.generator.ast.MessageDef readMessageDef(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { de.haumacher.msgbuf.generator.ast.MessageDef result = new de.haumacher.msgbuf.generator.ast.MessageDef(); result.readContent(in); return result; @@ -418,21 +461,21 @@ public static MessageDef readMessageDef(de.haumacher.msgbuf.json.JsonReader in) @Override protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { super.writeFields(out); - out.name(ABSTRACT); + out.name(ABSTRACT__PROP); out.value(isAbstract()); if (hasExtends()) { - out.name(EXTENDS); + out.name(EXTENDS__PROP); getExtends().writeTo(out); } - out.name(DEFINITIONS); + out.name(DEFINITIONS__PROP); out.beginArray(); - for (Definition x : getDefinitions()) { + for (de.haumacher.msgbuf.generator.ast.Definition x : getDefinitions()) { x.writeTo(out); } out.endArray(); - out.name(FIELDS); + out.name(FIELDS__PROP); out.beginArray(); - for (Field x : getFields()) { + for (de.haumacher.msgbuf.generator.ast.Field x : getFields()) { x.writeContent(out); } out.endArray(); @@ -441,22 +484,26 @@ protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java. @Override protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { switch (field) { - case ABSTRACT: setAbstract(in.nextBoolean()); break; - case EXTENDS: setExtends(de.haumacher.msgbuf.generator.ast.QName.readQName(in)); break; - case DEFINITIONS: { + case ABSTRACT__PROP: setAbstract(in.nextBoolean()); break; + case EXTENDS__PROP: setExtends(de.haumacher.msgbuf.generator.ast.QName.readQName(in)); break; + case DEFINITIONS__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); in.beginArray(); while (in.hasNext()) { - addDefinition(de.haumacher.msgbuf.generator.ast.Definition.readDefinition(in)); + newValue.add(de.haumacher.msgbuf.generator.ast.Definition.readDefinition(in)); } in.endArray(); + setDefinitions(newValue); } break; - case FIELDS: { + case FIELDS__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); in.beginArray(); while (in.hasNext()) { - addField(de.haumacher.msgbuf.generator.ast.Field.readField(in)); + newValue.add(de.haumacher.msgbuf.generator.ast.Field.readField(in)); } in.endArray(); + setFields(newValue); } break; default: super.readField(in, field); @@ -464,7 +511,12 @@ protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) t } @Override - public R visit(Definition.Visitor v, A arg) { + public MessageDef self() { + return this; + } + + @Override + public R visit(de.haumacher.msgbuf.generator.ast.Definition.Visitor v, A arg) { return v.visit(this, arg); } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/NumberOption.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/NumberOption.java index 95db9349..3e47cdde 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/NumberOption.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/NumberOption.java @@ -3,27 +3,27 @@ /** * {@link Option} annotating an int value */ -public class NumberOption extends Option { +public class NumberOption extends de.haumacher.msgbuf.generator.ast.Option { /** - * Creates a {@link NumberOption} instance. + * Creates a {@link de.haumacher.msgbuf.generator.ast.NumberOption} instance. */ - public static NumberOption create() { + public static de.haumacher.msgbuf.generator.ast.NumberOption create() { return new de.haumacher.msgbuf.generator.ast.NumberOption(); } - /** Identifier for the {@link NumberOption} type in JSON format. */ + /** Identifier for the {@link de.haumacher.msgbuf.generator.ast.NumberOption} type in JSON format. */ public static final String NUMBER_OPTION__TYPE = "NumberOption"; /** @see #getValue() */ - public static final String VALUE = "value"; + public static final String VALUE__PROP = "value"; private double _value = 0.0d; /** * Creates a {@link NumberOption} instance. * - * @see NumberOption#create() + * @see de.haumacher.msgbuf.generator.ast.NumberOption#create() */ protected NumberOption() { super(); @@ -44,15 +44,16 @@ public final double getValue() { /** * @see #getValue() */ - public NumberOption setValue(double value) { + public de.haumacher.msgbuf.generator.ast.NumberOption setValue(double value) { internalSetValue(value); return this; } /** Internal setter for {@link #getValue()} without chain call utility. */ protected final void internalSetValue(double value) { - _listener.beforeSet(this, VALUE, value); + _listener.beforeSet(this, VALUE__PROP, value); _value = value; + _listener.afterChanged(this, VALUE__PROP); } @Override @@ -60,19 +61,35 @@ public String jsonType() { return NUMBER_OPTION__TYPE; } - private static java.util.List PROPERTIES = java.util.Collections.unmodifiableList( - java.util.Arrays.asList( - VALUE)); + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + VALUE__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } @Override public java.util.List properties() { return PROPERTIES; } + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + @Override public Object get(String field) { switch (field) { - case VALUE: return getValue(); + case VALUE__PROP: return getValue(); default: return super.get(field); } } @@ -80,13 +97,13 @@ public Object get(String field) { @Override public void set(String field, Object value) { switch (field) { - case VALUE: internalSetValue((double) value); break; + case VALUE__PROP: internalSetValue((double) value); break; default: super.set(field, value); break; } } /** Reads a new instance from the given reader. */ - public static NumberOption readNumberOption(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + public static de.haumacher.msgbuf.generator.ast.NumberOption readNumberOption(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { de.haumacher.msgbuf.generator.ast.NumberOption result = new de.haumacher.msgbuf.generator.ast.NumberOption(); result.readContent(in); return result; @@ -95,20 +112,20 @@ public static NumberOption readNumberOption(de.haumacher.msgbuf.json.JsonReader @Override protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { super.writeFields(out); - out.name(VALUE); + out.name(VALUE__PROP); out.value(getValue()); } @Override protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { switch (field) { - case VALUE: setValue(in.nextDouble()); break; + case VALUE__PROP: setValue(in.nextDouble()); break; default: super.readField(in, field); } } @Override - public R visit(Option.Visitor v, A arg) { + public R visit(de.haumacher.msgbuf.generator.ast.Option.Visitor v, A arg) { return v.visit(this, arg); } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Option.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Option.java index 6053e5d4..d389ad2a 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Option.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Option.java @@ -9,32 +9,32 @@ */ public abstract class Option extends de.haumacher.msgbuf.data.AbstractDataObject implements de.haumacher.msgbuf.observer.Observable { - /** Type codes for the {@link Option} hierarchy. */ + /** Type codes for the {@link de.haumacher.msgbuf.generator.ast.Option} hierarchy. */ public enum TypeKind { - /** Type literal for {@link StringOption}. */ + /** Type literal for {@link de.haumacher.msgbuf.generator.ast.StringOption}. */ STRING_OPTION, - /** Type literal for {@link NumberOption}. */ + /** Type literal for {@link de.haumacher.msgbuf.generator.ast.NumberOption}. */ NUMBER_OPTION, - /** Type literal for {@link Flag}. */ + /** Type literal for {@link de.haumacher.msgbuf.generator.ast.Flag}. */ FLAG, ; } - /** Visitor interface for the {@link Option} hierarchy.*/ + /** Visitor interface for the {@link de.haumacher.msgbuf.generator.ast.Option} hierarchy.*/ public interface Visitor { - /** Visit case for {@link StringOption}.*/ - R visit(StringOption self, A arg); + /** Visit case for {@link de.haumacher.msgbuf.generator.ast.StringOption}.*/ + R visit(de.haumacher.msgbuf.generator.ast.StringOption self, A arg); - /** Visit case for {@link NumberOption}.*/ - R visit(NumberOption self, A arg); + /** Visit case for {@link de.haumacher.msgbuf.generator.ast.NumberOption}.*/ + R visit(de.haumacher.msgbuf.generator.ast.NumberOption self, A arg); - /** Visit case for {@link Flag}.*/ - R visit(Flag self, A arg); + /** Visit case for {@link de.haumacher.msgbuf.generator.ast.Flag}.*/ + R visit(de.haumacher.msgbuf.generator.ast.Flag self, A arg); } @@ -51,7 +51,7 @@ protected Option() { protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; @Override - public Option registerListener(de.haumacher.msgbuf.observer.Listener l) { + public de.haumacher.msgbuf.generator.ast.Option registerListener(de.haumacher.msgbuf.observer.Listener l) { internalRegisterListener(l); return this; } @@ -61,7 +61,7 @@ protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Liste } @Override - public Option unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + public de.haumacher.msgbuf.generator.ast.Option unregisterListener(de.haumacher.msgbuf.observer.Listener l) { internalUnregisterListener(l); return this; } @@ -71,8 +71,8 @@ protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Lis } /** Reads a new instance from the given reader. */ - public static Option readOption(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { - Option result; + public static de.haumacher.msgbuf.generator.ast.Option readOption(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + de.haumacher.msgbuf.generator.ast.Option result; in.beginArray(); String type = in.nextString(); switch (type) { diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/OptionContainer.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/OptionContainer.java index 208a00f2..574b97cf 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/OptionContainer.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/OptionContainer.java @@ -3,22 +3,22 @@ /** * Container for temporary collecting annotations without further semantics. */ -public class OptionContainer extends WithOptions { +public class OptionContainer extends de.haumacher.msgbuf.generator.ast.WithOptions { /** - * Creates a {@link OptionContainer} instance. + * Creates a {@link de.haumacher.msgbuf.generator.ast.OptionContainer} instance. */ - public static OptionContainer create() { + public static de.haumacher.msgbuf.generator.ast.OptionContainer create() { return new de.haumacher.msgbuf.generator.ast.OptionContainer(); } - /** Identifier for the {@link OptionContainer} type in JSON format. */ + /** Identifier for the {@link de.haumacher.msgbuf.generator.ast.OptionContainer} type in JSON format. */ public static final String OPTION_CONTAINER__TYPE = "OptionContainer"; /** * Creates a {@link OptionContainer} instance. * - * @see OptionContainer#create() + * @see de.haumacher.msgbuf.generator.ast.OptionContainer#create() */ protected OptionContainer() { super(); @@ -30,13 +30,13 @@ public TypeKind kind() { } @Override - public OptionContainer setOptions(java.util.Map value) { + public de.haumacher.msgbuf.generator.ast.OptionContainer setOptions(java.util.Map value) { internalSetOptions(value); return this; } @Override - public OptionContainer putOption(String key, Option value) { + public de.haumacher.msgbuf.generator.ast.OptionContainer putOption(String key, de.haumacher.msgbuf.generator.ast.Option value) { internalPutOption(key, value); return this; } @@ -47,14 +47,14 @@ public String jsonType() { } /** Reads a new instance from the given reader. */ - public static OptionContainer readOptionContainer(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + public static de.haumacher.msgbuf.generator.ast.OptionContainer readOptionContainer(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { de.haumacher.msgbuf.generator.ast.OptionContainer result = new de.haumacher.msgbuf.generator.ast.OptionContainer(); result.readContent(in); return result; } @Override - public R visit(WithOptions.Visitor v, A arg) { + public R visit(de.haumacher.msgbuf.generator.ast.WithOptions.Visitor v, A arg) { return v.visit(this, arg); } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Part.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Part.java index f0800548..a49a2424 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Part.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Part.java @@ -3,33 +3,33 @@ /** * Member of a {@link Definition}. */ -public abstract class Part extends DefinitionBase { +public abstract class Part extends de.haumacher.msgbuf.generator.ast.DefinitionBase { - /** Visitor interface for the {@link Part} hierarchy.*/ + /** Visitor interface for the {@link de.haumacher.msgbuf.generator.ast.Part} hierarchy.*/ public interface Visitor { - /** Visit case for {@link Constant}.*/ - R visit(Constant self, A arg); + /** Visit case for {@link de.haumacher.msgbuf.generator.ast.Constant}.*/ + R visit(de.haumacher.msgbuf.generator.ast.Constant self, A arg); - /** Visit case for {@link Field}.*/ - R visit(Field self, A arg); + /** Visit case for {@link de.haumacher.msgbuf.generator.ast.Field}.*/ + R visit(de.haumacher.msgbuf.generator.ast.Field self, A arg); } /** @see #getName() */ - public static final String NAME = "name"; + public static final String NAME__PROP = "name"; /** @see #getIndex() */ - public static final String INDEX = "index"; + public static final String INDEX__PROP = "index"; /** @see #getOwner() */ - public static final String OWNER = "owner"; + public static final String OWNER__PROP = "owner"; private String _name = ""; private int _index = 0; - private transient Definition _owner = null; + private transient de.haumacher.msgbuf.generator.ast.Definition _owner = null; /** * Creates a {@link Part} instance. @@ -48,19 +48,20 @@ public final String getName() { /** * @see #getName() */ - public Part setName(String value) { + public de.haumacher.msgbuf.generator.ast.Part setName(String value) { internalSetName(value); return this; } /** Internal setter for {@link #getName()} without chain call utility. */ protected final void internalSetName(String value) { - _listener.beforeSet(this, NAME, value); + _listener.beforeSet(this, NAME__PROP, value); _name = value; + _listener.afterChanged(this, NAME__PROP); } /** - * The numeric identifier for this member. + * The numeric index for binary serialization. */ public final int getIndex() { return _index; @@ -69,36 +70,38 @@ public final int getIndex() { /** * @see #getIndex() */ - public Part setIndex(int value) { + public de.haumacher.msgbuf.generator.ast.Part setIndex(int value) { internalSetIndex(value); return this; } /** Internal setter for {@link #getIndex()} without chain call utility. */ protected final void internalSetIndex(int value) { - _listener.beforeSet(this, INDEX, value); + _listener.beforeSet(this, INDEX__PROP, value); _index = value; + _listener.afterChanged(this, INDEX__PROP); } /** * The {@link Definition} definint this {@link Part}. */ - public final Definition getOwner() { + public final de.haumacher.msgbuf.generator.ast.Definition getOwner() { return _owner; } /** * @see #getOwner() */ - public Part setOwner(Definition value) { + public de.haumacher.msgbuf.generator.ast.Part setOwner(de.haumacher.msgbuf.generator.ast.Definition value) { internalSetOwner(value); return this; } /** Internal setter for {@link #getOwner()} without chain call utility. */ - protected final void internalSetOwner(Definition value) { - _listener.beforeSet(this, OWNER, value); + protected final void internalSetOwner(de.haumacher.msgbuf.generator.ast.Definition value) { + _listener.beforeSet(this, OWNER__PROP, value); _owner = value; + _listener.afterChanged(this, OWNER__PROP); } /** @@ -109,40 +112,62 @@ public final boolean hasOwner() { } @Override - public Part setComment(String value) { + public de.haumacher.msgbuf.generator.ast.Part setComment(String value) { internalSetComment(value); return this; } @Override - public Part setOptions(java.util.Map value) { + public de.haumacher.msgbuf.generator.ast.Part setOptions(java.util.Map value) { internalSetOptions(value); return this; } @Override - public Part putOption(String key, Option value) { + public de.haumacher.msgbuf.generator.ast.Part putOption(String key, de.haumacher.msgbuf.generator.ast.Option value) { internalPutOption(key, value); return this; } - private static java.util.List PROPERTIES = java.util.Collections.unmodifiableList( - java.util.Arrays.asList( - NAME, - INDEX, - OWNER)); + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + NAME__PROP, + INDEX__PROP, + OWNER__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(de.haumacher.msgbuf.generator.ast.DefinitionBase.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(de.haumacher.msgbuf.generator.ast.DefinitionBase.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + OWNER__PROP)); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } @Override public java.util.List properties() { return PROPERTIES; } + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + @Override public Object get(String field) { switch (field) { - case NAME: return getName(); - case INDEX: return getIndex(); - case OWNER: return getOwner(); + case NAME__PROP: return getName(); + case INDEX__PROP: return getIndex(); + case OWNER__PROP: return getOwner(); default: return super.get(field); } } @@ -150,16 +175,16 @@ public Object get(String field) { @Override public void set(String field, Object value) { switch (field) { - case NAME: internalSetName((String) value); break; - case INDEX: internalSetIndex((int) value); break; - case OWNER: internalSetOwner((Definition) value); break; + case NAME__PROP: internalSetName((String) value); break; + case INDEX__PROP: internalSetIndex((int) value); break; + case OWNER__PROP: internalSetOwner((de.haumacher.msgbuf.generator.ast.Definition) value); break; default: super.set(field, value); break; } } /** Reads a new instance from the given reader. */ - public static Part readPart(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { - Part result; + public static de.haumacher.msgbuf.generator.ast.Part readPart(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + de.haumacher.msgbuf.generator.ast.Part result; in.beginArray(); String type = in.nextString(); switch (type) { @@ -174,17 +199,17 @@ public static Part readPart(de.haumacher.msgbuf.json.JsonReader in) throws java. @Override protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { super.writeFields(out); - out.name(NAME); + out.name(NAME__PROP); out.value(getName()); - out.name(INDEX); + out.name(INDEX__PROP); out.value(getIndex()); } @Override protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { switch (field) { - case NAME: setName(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; - case INDEX: setIndex(in.nextInt()); break; + case NAME__PROP: setName(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + case INDEX__PROP: setIndex(in.nextInt()); break; default: super.readField(in, field); } } @@ -193,8 +218,8 @@ protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) t public abstract R visit(Visitor v, A arg); @Override - public final R visit(DefinitionBase.Visitor v, A arg) { - return visit((Part.Visitor) v, arg); + public final R visit(de.haumacher.msgbuf.generator.ast.DefinitionBase.Visitor v, A arg) { + return visit((de.haumacher.msgbuf.generator.ast.Part.Visitor) v, arg); } } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/PrimitiveType.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/PrimitiveType.java index ac7f8061..503668e7 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/PrimitiveType.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/PrimitiveType.java @@ -3,7 +3,7 @@ /** * A primitive built-in {@link Type}. */ -public class PrimitiveType extends Type { +public class PrimitiveType extends de.haumacher.msgbuf.generator.ast.Type { /** * Supported built-in types. @@ -85,6 +85,11 @@ public enum Kind implements de.haumacher.msgbuf.data.ProtocolEnum { */ BYTES("BYTES"), + /** + * An opaque JSON value (any valid JSON: object, array, string, number, boolean, null). + */ + JSON("JSON"), + ; private final String _protocolName; @@ -122,6 +127,7 @@ public static Kind valueOfProtocol(String protocolName) { case "FLOAT": return FLOAT; case "DOUBLE": return DOUBLE; case "BYTES": return BYTES; + case "JSON": return JSON; } return INT_32; } @@ -154,6 +160,7 @@ public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java case FLOAT: out.value(13); break; case DOUBLE: out.value(14); break; case BYTES: out.value(15); break; + case JSON: out.value(16); break; default: out.value(0); } } @@ -176,30 +183,31 @@ public static Kind readKind(de.haumacher.msgbuf.binary.DataReader in) throws jav case 13: return FLOAT; case 14: return DOUBLE; case 15: return BYTES; + case 16: return JSON; default: return INT_32; } } } /** - * Creates a {@link PrimitiveType} instance. + * Creates a {@link de.haumacher.msgbuf.generator.ast.PrimitiveType} instance. */ - public static PrimitiveType create() { + public static de.haumacher.msgbuf.generator.ast.PrimitiveType create() { return new de.haumacher.msgbuf.generator.ast.PrimitiveType(); } - /** Identifier for the {@link PrimitiveType} type in JSON format. */ + /** Identifier for the {@link de.haumacher.msgbuf.generator.ast.PrimitiveType} type in JSON format. */ public static final String PRIMITIVE_TYPE__TYPE = "PrimitiveType"; /** @see #getKind() */ - public static final String KIND = "kind"; + public static final String KIND__PROP = "kind"; - private Kind _kind = de.haumacher.msgbuf.generator.ast.PrimitiveType.Kind.INT_32; + private de.haumacher.msgbuf.generator.ast.PrimitiveType.Kind _kind = de.haumacher.msgbuf.generator.ast.PrimitiveType.Kind.INT_32; /** * Creates a {@link PrimitiveType} instance. * - * @see PrimitiveType#create() + * @see de.haumacher.msgbuf.generator.ast.PrimitiveType#create() */ protected PrimitiveType() { super(); @@ -213,23 +221,24 @@ public TypeKind kind() { /** * The type kind. */ - public final Kind getKind() { + public final de.haumacher.msgbuf.generator.ast.PrimitiveType.Kind getKind() { return _kind; } /** * @see #getKind() */ - public PrimitiveType setKind(Kind value) { + public de.haumacher.msgbuf.generator.ast.PrimitiveType setKind(de.haumacher.msgbuf.generator.ast.PrimitiveType.Kind value) { internalSetKind(value); return this; } /** Internal setter for {@link #getKind()} without chain call utility. */ - protected final void internalSetKind(Kind value) { + protected final void internalSetKind(de.haumacher.msgbuf.generator.ast.PrimitiveType.Kind value) { if (value == null) throw new IllegalArgumentException("Property 'kind' cannot be null."); - _listener.beforeSet(this, KIND, value); + _listener.beforeSet(this, KIND__PROP, value); _kind = value; + _listener.afterChanged(this, KIND__PROP); } @Override @@ -237,19 +246,35 @@ public String jsonType() { return PRIMITIVE_TYPE__TYPE; } - private static java.util.List PROPERTIES = java.util.Collections.unmodifiableList( - java.util.Arrays.asList( - KIND)); + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + KIND__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } @Override public java.util.List properties() { return PROPERTIES; } + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + @Override public Object get(String field) { switch (field) { - case KIND: return getKind(); + case KIND__PROP: return getKind(); default: return super.get(field); } } @@ -257,13 +282,13 @@ public Object get(String field) { @Override public void set(String field, Object value) { switch (field) { - case KIND: internalSetKind((Kind) value); break; + case KIND__PROP: internalSetKind((de.haumacher.msgbuf.generator.ast.PrimitiveType.Kind) value); break; default: super.set(field, value); break; } } /** Reads a new instance from the given reader. */ - public static PrimitiveType readPrimitiveType(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + public static de.haumacher.msgbuf.generator.ast.PrimitiveType readPrimitiveType(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { de.haumacher.msgbuf.generator.ast.PrimitiveType result = new de.haumacher.msgbuf.generator.ast.PrimitiveType(); result.readContent(in); return result; @@ -272,20 +297,20 @@ public static PrimitiveType readPrimitiveType(de.haumacher.msgbuf.json.JsonReade @Override protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { super.writeFields(out); - out.name(KIND); + out.name(KIND__PROP); getKind().writeTo(out); } @Override protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { switch (field) { - case KIND: setKind(de.haumacher.msgbuf.generator.ast.PrimitiveType.Kind.readKind(in)); break; + case KIND__PROP: setKind(de.haumacher.msgbuf.generator.ast.PrimitiveType.Kind.readKind(in)); break; default: super.readField(in, field); } } @Override - public R visit(Type.Visitor v, A arg) { + public R visit(de.haumacher.msgbuf.generator.ast.Type.Visitor v, A arg) { return v.visit(this, arg); } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/QName.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/QName.java index 29350803..c7a9c6ed 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/QName.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/QName.java @@ -6,34 +6,39 @@ public class QName extends de.haumacher.msgbuf.data.AbstractDataObject implements de.haumacher.msgbuf.observer.Observable { /** - * Creates a {@link QName} instance. + * Creates a {@link de.haumacher.msgbuf.generator.ast.QName} instance. */ - public static QName create() { + public static de.haumacher.msgbuf.generator.ast.QName create() { return new de.haumacher.msgbuf.generator.ast.QName(); } - /** Identifier for the {@link QName} type in JSON format. */ + /** Identifier for the {@link de.haumacher.msgbuf.generator.ast.QName} type in JSON format. */ public static final String QNAME__TYPE = "QName"; /** @see #getNames() */ - public static final String NAMES = "names"; + public static final String NAMES__PROP = "names"; private final java.util.List _names = new de.haumacher.msgbuf.util.ReferenceList() { @Override protected void beforeAdd(int index, String element) { - _listener.beforeAdd(QName.this, NAMES, index, element); + _listener.beforeAdd(QName.this, NAMES__PROP, index, element); } @Override protected void afterRemove(int index, String element) { - _listener.afterRemove(QName.this, NAMES, index, element); + _listener.afterRemove(QName.this, NAMES__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(QName.this, NAMES__PROP); } }; /** * Creates a {@link QName} instance. * - * @see QName#create() + * @see de.haumacher.msgbuf.generator.ast.QName#create() */ protected QName() { super(); @@ -49,7 +54,7 @@ public final java.util.List getNames() { /** * @see #getNames() */ - public QName setNames(java.util.List value) { + public de.haumacher.msgbuf.generator.ast.QName setNames(java.util.List value) { internalSetNames(value); return this; } @@ -63,7 +68,7 @@ protected final void internalSetNames(java.util.List value) { /** * Adds a value to the {@link #getNames()} list. */ - public QName addName(String value) { + public de.haumacher.msgbuf.generator.ast.QName addName(String value) { internalAddName(value); return this; } @@ -83,7 +88,7 @@ public final void removeName(String value) { protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; @Override - public QName registerListener(de.haumacher.msgbuf.observer.Listener l) { + public de.haumacher.msgbuf.generator.ast.QName registerListener(de.haumacher.msgbuf.observer.Listener l) { internalRegisterListener(l); return this; } @@ -93,7 +98,7 @@ protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Liste } @Override - public QName unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + public de.haumacher.msgbuf.generator.ast.QName unregisterListener(de.haumacher.msgbuf.observer.Listener l) { internalUnregisterListener(l); return this; } @@ -107,19 +112,35 @@ public String jsonType() { return QNAME__TYPE; } - private static java.util.List PROPERTIES = java.util.Collections.unmodifiableList( - java.util.Arrays.asList( - NAMES)); + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + NAMES__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } @Override public java.util.List properties() { return PROPERTIES; } + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + @Override public Object get(String field) { switch (field) { - case NAMES: return getNames(); + case NAMES__PROP: return getNames(); default: return null; } } @@ -127,12 +148,12 @@ public Object get(String field) { @Override public void set(String field, Object value) { switch (field) { - case NAMES: internalSetNames(de.haumacher.msgbuf.util.Conversions.asList(String.class, value)); break; + case NAMES__PROP: internalSetNames(de.haumacher.msgbuf.util.Conversions.asList(String.class, value)); break; } } /** Reads a new instance from the given reader. */ - public static QName readQName(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + public static de.haumacher.msgbuf.generator.ast.QName readQName(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { de.haumacher.msgbuf.generator.ast.QName result = new de.haumacher.msgbuf.generator.ast.QName(); result.readContent(in); return result; @@ -146,7 +167,7 @@ public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.i @Override protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { super.writeFields(out); - out.name(NAMES); + out.name(NAMES__PROP); out.beginArray(); for (String x : getNames()) { out.value(x); @@ -157,12 +178,14 @@ protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java. @Override protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { switch (field) { - case NAMES: { + case NAMES__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); in.beginArray(); while (in.hasNext()) { - addName(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); + newValue.add(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); } in.endArray(); + setNames(newValue); } break; default: super.readField(in, field); diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/StringOption.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/StringOption.java index 70303206..0409d949 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/StringOption.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/StringOption.java @@ -3,27 +3,27 @@ /** * {@link Option} annotating a string value */ -public class StringOption extends Option { +public class StringOption extends de.haumacher.msgbuf.generator.ast.Option { /** - * Creates a {@link StringOption} instance. + * Creates a {@link de.haumacher.msgbuf.generator.ast.StringOption} instance. */ - public static StringOption create() { + public static de.haumacher.msgbuf.generator.ast.StringOption create() { return new de.haumacher.msgbuf.generator.ast.StringOption(); } - /** Identifier for the {@link StringOption} type in JSON format. */ + /** Identifier for the {@link de.haumacher.msgbuf.generator.ast.StringOption} type in JSON format. */ public static final String STRING_OPTION__TYPE = "StringOption"; /** @see #getValue() */ - public static final String VALUE = "value"; + public static final String VALUE__PROP = "value"; private String _value = ""; /** * Creates a {@link StringOption} instance. * - * @see StringOption#create() + * @see de.haumacher.msgbuf.generator.ast.StringOption#create() */ protected StringOption() { super(); @@ -44,15 +44,16 @@ public final String getValue() { /** * @see #getValue() */ - public StringOption setValue(String value) { + public de.haumacher.msgbuf.generator.ast.StringOption setValue(String value) { internalSetValue(value); return this; } /** Internal setter for {@link #getValue()} without chain call utility. */ protected final void internalSetValue(String value) { - _listener.beforeSet(this, VALUE, value); + _listener.beforeSet(this, VALUE__PROP, value); _value = value; + _listener.afterChanged(this, VALUE__PROP); } @Override @@ -60,19 +61,35 @@ public String jsonType() { return STRING_OPTION__TYPE; } - private static java.util.List PROPERTIES = java.util.Collections.unmodifiableList( - java.util.Arrays.asList( - VALUE)); + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + VALUE__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } @Override public java.util.List properties() { return PROPERTIES; } + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + @Override public Object get(String field) { switch (field) { - case VALUE: return getValue(); + case VALUE__PROP: return getValue(); default: return super.get(field); } } @@ -80,13 +97,13 @@ public Object get(String field) { @Override public void set(String field, Object value) { switch (field) { - case VALUE: internalSetValue((String) value); break; + case VALUE__PROP: internalSetValue((String) value); break; default: super.set(field, value); break; } } /** Reads a new instance from the given reader. */ - public static StringOption readStringOption(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + public static de.haumacher.msgbuf.generator.ast.StringOption readStringOption(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { de.haumacher.msgbuf.generator.ast.StringOption result = new de.haumacher.msgbuf.generator.ast.StringOption(); result.readContent(in); return result; @@ -95,20 +112,20 @@ public static StringOption readStringOption(de.haumacher.msgbuf.json.JsonReader @Override protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { super.writeFields(out); - out.name(VALUE); + out.name(VALUE__PROP); out.value(getValue()); } @Override protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { switch (field) { - case VALUE: setValue(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + case VALUE__PROP: setValue(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; default: super.readField(in, field); } } @Override - public R visit(Option.Visitor v, A arg) { + public R visit(de.haumacher.msgbuf.generator.ast.Option.Visitor v, A arg) { return v.visit(this, arg); } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Type.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Type.java index c6302235..8b402034 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Type.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/Type.java @@ -5,32 +5,32 @@ */ public abstract class Type extends de.haumacher.msgbuf.data.AbstractDataObject implements de.haumacher.msgbuf.observer.Observable { - /** Type codes for the {@link Type} hierarchy. */ + /** Type codes for the {@link de.haumacher.msgbuf.generator.ast.Type} hierarchy. */ public enum TypeKind { - /** Type literal for {@link CustomType}. */ + /** Type literal for {@link de.haumacher.msgbuf.generator.ast.CustomType}. */ CUSTOM_TYPE, - /** Type literal for {@link PrimitiveType}. */ + /** Type literal for {@link de.haumacher.msgbuf.generator.ast.PrimitiveType}. */ PRIMITIVE_TYPE, - /** Type literal for {@link MapType}. */ + /** Type literal for {@link de.haumacher.msgbuf.generator.ast.MapType}. */ MAP_TYPE, ; } - /** Visitor interface for the {@link Type} hierarchy.*/ + /** Visitor interface for the {@link de.haumacher.msgbuf.generator.ast.Type} hierarchy.*/ public interface Visitor { - /** Visit case for {@link CustomType}.*/ - R visit(CustomType self, A arg); + /** Visit case for {@link de.haumacher.msgbuf.generator.ast.CustomType}.*/ + R visit(de.haumacher.msgbuf.generator.ast.CustomType self, A arg); - /** Visit case for {@link PrimitiveType}.*/ - R visit(PrimitiveType self, A arg); + /** Visit case for {@link de.haumacher.msgbuf.generator.ast.PrimitiveType}.*/ + R visit(de.haumacher.msgbuf.generator.ast.PrimitiveType self, A arg); - /** Visit case for {@link MapType}.*/ - R visit(MapType self, A arg); + /** Visit case for {@link de.haumacher.msgbuf.generator.ast.MapType}.*/ + R visit(de.haumacher.msgbuf.generator.ast.MapType self, A arg); } @@ -47,7 +47,7 @@ protected Type() { protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; @Override - public Type registerListener(de.haumacher.msgbuf.observer.Listener l) { + public de.haumacher.msgbuf.generator.ast.Type registerListener(de.haumacher.msgbuf.observer.Listener l) { internalRegisterListener(l); return this; } @@ -57,7 +57,7 @@ protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Liste } @Override - public Type unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + public de.haumacher.msgbuf.generator.ast.Type unregisterListener(de.haumacher.msgbuf.observer.Listener l) { internalUnregisterListener(l); return this; } @@ -67,8 +67,8 @@ protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Lis } /** Reads a new instance from the given reader. */ - public static Type readType(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { - Type result; + public static de.haumacher.msgbuf.generator.ast.Type readType(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + de.haumacher.msgbuf.generator.ast.Type result; in.beginArray(); String type = in.nextString(); switch (type) { diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/WithOptions.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/WithOptions.java index 2e301d11..e1b9bd01 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/WithOptions.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/WithOptions.java @@ -5,45 +5,60 @@ */ public abstract class WithOptions extends de.haumacher.msgbuf.data.AbstractDataObject implements de.haumacher.msgbuf.observer.Observable { - /** Type codes for the {@link WithOptions} hierarchy. */ + /** Type codes for the {@link de.haumacher.msgbuf.generator.ast.WithOptions} hierarchy. */ public enum TypeKind { - /** Type literal for {@link OptionContainer}. */ + /** Type literal for {@link de.haumacher.msgbuf.generator.ast.OptionContainer}. */ OPTION_CONTAINER, - /** Type literal for {@link Constant}. */ + /** Type literal for {@link de.haumacher.msgbuf.generator.ast.Constant}. */ CONSTANT, - /** Type literal for {@link Field}. */ + /** Type literal for {@link de.haumacher.msgbuf.generator.ast.Field}. */ FIELD, - /** Type literal for {@link EnumDef}. */ + /** Type literal for {@link de.haumacher.msgbuf.generator.ast.EnumDef}. */ ENUM_DEF, - /** Type literal for {@link MessageDef}. */ + /** Type literal for {@link de.haumacher.msgbuf.generator.ast.MessageDef}. */ MESSAGE_DEF, - /** Type literal for {@link DefinitionFile}. */ + /** Type literal for {@link de.haumacher.msgbuf.generator.ast.DefinitionFile}. */ DEFINITION_FILE, ; } - /** Visitor interface for the {@link WithOptions} hierarchy.*/ - public interface Visitor extends DefinitionBase.Visitor { + /** Visitor interface for the {@link de.haumacher.msgbuf.generator.ast.WithOptions} hierarchy.*/ + public interface Visitor extends de.haumacher.msgbuf.generator.ast.DefinitionBase.Visitor { - /** Visit case for {@link OptionContainer}.*/ - R visit(OptionContainer self, A arg); + /** Visit case for {@link de.haumacher.msgbuf.generator.ast.OptionContainer}.*/ + R visit(de.haumacher.msgbuf.generator.ast.OptionContainer self, A arg); - /** Visit case for {@link DefinitionFile}.*/ - R visit(DefinitionFile self, A arg); + /** Visit case for {@link de.haumacher.msgbuf.generator.ast.DefinitionFile}.*/ + R visit(de.haumacher.msgbuf.generator.ast.DefinitionFile self, A arg); } /** @see #getOptions() */ - public static final String OPTIONS = "options"; + public static final String OPTIONS__PROP = "options"; - private final java.util.Map _options = new java.util.HashMap<>(); + private final java.util.Map _options = new de.haumacher.msgbuf.util.ReferenceMap() { + @Override + protected void beforeAdd(String index, de.haumacher.msgbuf.generator.ast.Option element) { + _listener.beforeAdd(WithOptions.this, OPTIONS__PROP, index, element); + } + + @Override + protected void afterRemove(String index, de.haumacher.msgbuf.generator.ast.Option element) { + _listener.afterRemove(WithOptions.this, OPTIONS__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(WithOptions.this, OPTIONS__PROP); + } + }; /** * Creates a {@link WithOptions} instance. @@ -58,20 +73,20 @@ protected WithOptions() { /** * Annotations to this definition. */ - public final java.util.Map getOptions() { + public final java.util.Map getOptions() { return _options; } /** * @see #getOptions() */ - public WithOptions setOptions(java.util.Map value) { + public de.haumacher.msgbuf.generator.ast.WithOptions setOptions(java.util.Map value) { internalSetOptions(value); return this; } /** Internal setter for {@link #getOptions()} without chain call utility. */ - protected final void internalSetOptions(java.util.Map value) { + protected final void internalSetOptions(java.util.Map value) { if (value == null) throw new IllegalArgumentException("Property 'options' cannot be null."); _options.clear(); _options.putAll(value); @@ -80,13 +95,13 @@ protected final void internalSetOptions(java.util.Map value) { /** * Adds a key value pair to the {@link #getOptions()} map. */ - public WithOptions putOption(String key, Option value) { + public de.haumacher.msgbuf.generator.ast.WithOptions putOption(String key, de.haumacher.msgbuf.generator.ast.Option value) { internalPutOption(key, value); return this; } - /** Implementation of {@link #putOption(String, Option)} without chain call utility. */ - protected final void internalPutOption(String key, Option value) { + /** Implementation of {@link #putOption(String, de.haumacher.msgbuf.generator.ast.Option)} without chain call utility. */ + protected final void internalPutOption(String key, de.haumacher.msgbuf.generator.ast.Option value) { if (_options.containsKey(key)) { throw new IllegalArgumentException("Property 'options' already contains a value for key '" + key + "'."); } @@ -103,7 +118,7 @@ public final void removeOption(String key) { protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; @Override - public WithOptions registerListener(de.haumacher.msgbuf.observer.Listener l) { + public de.haumacher.msgbuf.generator.ast.WithOptions registerListener(de.haumacher.msgbuf.observer.Listener l) { internalRegisterListener(l); return this; } @@ -113,7 +128,7 @@ protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Liste } @Override - public WithOptions unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + public de.haumacher.msgbuf.generator.ast.WithOptions unregisterListener(de.haumacher.msgbuf.observer.Listener l) { internalUnregisterListener(l); return this; } @@ -122,19 +137,35 @@ protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Lis _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); } - private static java.util.List PROPERTIES = java.util.Collections.unmodifiableList( - java.util.Arrays.asList( - OPTIONS)); + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + OPTIONS__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } @Override public java.util.List properties() { return PROPERTIES; } + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + @Override public Object get(String field) { switch (field) { - case OPTIONS: return getOptions(); + case OPTIONS__PROP: return getOptions(); default: return null; } } @@ -142,22 +173,22 @@ public Object get(String field) { @Override public void set(String field, Object value) { switch (field) { - case OPTIONS: internalSetOptions((java.util.Map) value); break; + case OPTIONS__PROP: internalSetOptions((java.util.Map) value); break; } } /** Reads a new instance from the given reader. */ - public static WithOptions readWithOptions(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { - WithOptions result; + public static de.haumacher.msgbuf.generator.ast.WithOptions readWithOptions(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + de.haumacher.msgbuf.generator.ast.WithOptions result; in.beginArray(); String type = in.nextString(); switch (type) { case OptionContainer.OPTION_CONTAINER__TYPE: result = de.haumacher.msgbuf.generator.ast.OptionContainer.readOptionContainer(in); break; - case DefinitionFile.DEFINITION_FILE__TYPE: result = de.haumacher.msgbuf.generator.ast.DefinitionFile.readDefinitionFile(in); break; case Constant.CONSTANT__TYPE: result = de.haumacher.msgbuf.generator.ast.Constant.readConstant(in); break; case Field.FIELD__TYPE: result = de.haumacher.msgbuf.generator.ast.Field.readField(in); break; case EnumDef.ENUM_DEF__TYPE: result = de.haumacher.msgbuf.generator.ast.EnumDef.readEnumDef(in); break; case MessageDef.MESSAGE_DEF__TYPE: result = de.haumacher.msgbuf.generator.ast.MessageDef.readMessageDef(in); break; + case DefinitionFile.DEFINITION_FILE__TYPE: result = de.haumacher.msgbuf.generator.ast.DefinitionFile.readDefinitionFile(in); break; default: in.skipValue(); result = null; break; } in.endArray(); @@ -175,9 +206,9 @@ public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.i @Override protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { super.writeFields(out); - out.name(OPTIONS); + out.name(OPTIONS__PROP); out.beginObject(); - for (java.util.Map.Entry entry : getOptions().entrySet()) { + for (java.util.Map.Entry entry : getOptions().entrySet()) { out.name(entry.getKey()); entry.getValue().writeTo(out); } @@ -187,12 +218,14 @@ protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java. @Override protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { switch (field) { - case OPTIONS: { + case OPTIONS__PROP: { + java.util.Map newValue = new java.util.LinkedHashMap<>(); in.beginObject(); while (in.hasNext()) { - putOption(in.nextName(), de.haumacher.msgbuf.generator.ast.Option.readOption(in)); + newValue.put(in.nextName(), de.haumacher.msgbuf.generator.ast.Option.readOption(in)); } in.endObject(); + setOptions(newValue); break; } default: super.readField(in, field); diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/proto.proto b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/proto.proto index e64ec1d0..79982609 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/proto.proto +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/proto.proto @@ -1,6 +1,7 @@ package de.haumacher.msgbuf.generator.ast; option NoBinary; +option NoXml; option NoReflection; option NoVisitorExceptions; option NoInterfaces; @@ -27,10 +28,10 @@ abstract message DefinitionBase extends WithOptions { abstract message Part extends DefinitionBase { /** The name of this member. */ string name; - - /** The numeric identifier for this member.*/ + + /** The numeric index for binary serialization. */ int index; - + /** The {@link Definition} definint this {@link Part}. */ transient Definition owner; } @@ -41,7 +42,7 @@ abstract message Part extends DefinitionBase { * @see EnumDef#constants */ message Constant extends Part { - // No additional members. + } /** @@ -50,9 +51,15 @@ message Constant extends Part { * @see #definitions */ message DefinitionFile extends WithOptions { + /** The documentation comment of the file (the doc comment before the syntax or package declaration). */ + string comment; + /** The package name for all types in this file. */ QName `package`; - + + /** Import paths referencing other .proto files. */ + repeated string imports; + /** All definitions in this file. */ repeated Definition definitions; } @@ -88,6 +95,7 @@ message EnumDef extends Definition { /** * {@link Definition} of a data class. */ +@Operations("de.haumacher.msgbuf.generator.MessageDefOperations") message MessageDef extends Definition { /** Whether this class only serves as super type for other data classes. */ boolean `abstract`; @@ -134,6 +142,10 @@ message Field extends Part { /** The type of values that can be stored in this field. */ Type type; + /** The initializer value to assign to the field. */ + @Nullable + string defaultValue; + } /** @@ -207,6 +219,9 @@ message PrimitiveType extends Type { /** A string of octets. */ BYTES; + + /** An opaque JSON value (any valid JSON: object, array, string, number, boolean, null). */ + JSON; } /** The type kind. */ diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/common/DocTags.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/common/DocTags.java new file mode 100644 index 00000000..1e8b1d96 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/common/DocTags.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2026 Bernhard Haumacher et al. All Rights Reserved. + */ +package de.haumacher.msgbuf.generator.common; + +/** + * Utility for processing JavaDoc-style inline tags ({@literal {@tag content}}) in + * documentation comments of protocol definitions. + */ +public class DocTags { + + /** + * Callback computing the replacement of an inline tag. + */ + public interface TagReplacement { + + /** + * Computes the replacement text for an inline tag. + * + * @param tag + * The tag name without @, e.g. link. + * @param content + * The text after the tag name, with surrounding white space removed. + * @return The replacement text, or null to keep the tag unchanged. + */ + String replace(String tag, String content); + } + + /** + * Replaces all inline tags in the given comment. + * + *

+ * Braces within the tag content are matched, so {@literal {@code {a: 1}}} is a + * single tag. An unterminated tag is kept unchanged. + *

+ */ + public static String replaceInlineTags(String comment, TagReplacement replacement) { + if (comment == null || comment.indexOf("{@") < 0) { + return comment; + } + StringBuilder result = new StringBuilder(); + int pos = 0; + int length = comment.length(); + while (pos < length) { + int start = comment.indexOf("{@", pos); + if (start < 0) { + break; + } + int end = closingBrace(comment, start); + if (end < 0) { + break; + } + result.append(comment, pos, start); + + int nameStart = start + 2; + int nameEnd = nameStart; + while (nameEnd < end && Character.isLetterOrDigit(comment.charAt(nameEnd))) { + nameEnd++; + } + String tag = comment.substring(nameStart, nameEnd); + String content = comment.substring(nameEnd, end).trim(); + String replaced = tag.isEmpty() ? null : replacement.replace(tag, content); + result.append(replaced == null ? comment.substring(start, end + 1) : replaced); + + pos = end + 1; + } + result.append(comment, pos, length); + return result.toString(); + } + + private static int closingBrace(String comment, int start) { + int depth = 0; + for (int n = start, cnt = comment.length(); n < cnt; n++) { + char ch = comment.charAt(n); + if (ch == '{') { + depth++; + } else if (ch == '}') { + depth--; + if (depth == 0) { + return n; + } + } + } + return -1; + } + +} 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 3ae43630..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,12 +11,14 @@ 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; import de.haumacher.msgbuf.generator.ast.MessageDef; import de.haumacher.msgbuf.generator.ast.Option; import de.haumacher.msgbuf.generator.ast.Part; +import de.haumacher.msgbuf.generator.ast.PrimitiveType; import de.haumacher.msgbuf.generator.ast.QName; import de.haumacher.msgbuf.generator.ast.Type; import de.haumacher.msgbuf.generator.ast.WithOptions; @@ -44,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) { @@ -58,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(); } @@ -75,7 +111,23 @@ 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; + } return type instanceof CustomType && !isEnumType(type); } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/dart/DartClassGenerator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/dart/DartClassGenerator.java index 0979cdc9..0c0825ec 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/dart/DartClassGenerator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/dart/DartClassGenerator.java @@ -5,6 +5,8 @@ import static de.haumacher.msgbuf.generator.dart.DartCoding.*; +import java.util.ArrayList; +import java.util.List; import java.util.stream.Collectors; import de.haumacher.msgbuf.generator.ast.Field; @@ -55,13 +57,23 @@ protected void generate() { nl(); } + List inheritedFields = new ArrayList<>(); + MessageDef superDef = _def.getExtendedDef(); + while (superDef != null) { + inheritedFields.addAll(superDef.getFields()); + superDef = superDef.getExtendedDef(); + } + line("/// Creates a " + typeName + "."); - if (_def.getFields().isEmpty()) { + if (_def.getFields().isEmpty() && inheritedFields.isEmpty()) { line(typeName + "();"); } else { line(typeName + "({"); + for (Field field : inheritedFields) { + line("super." + fieldName(field) + ","); + } for (Field field : _def.getFields()) { - line("this." + fieldName(field) + initializer(field) + ", "); + line("this." + fieldName(field) + initializer(field) + ","); } line("});"); } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/dart/DartCoding.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/dart/DartCoding.java index 28e54017..dd9de697 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/dart/DartCoding.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/dart/DartCoding.java @@ -22,7 +22,7 @@ public class DartCoding { * Name of an enum literal. */ public static String literalName(Constant constant) { - return firstLowerCase(camelCase(constant.getName())); + return firstLowerCase(camelCase(underscored(constant.getName()))); } /** diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/dart/InitializerGenerator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/dart/InitializerGenerator.java index bfb75b9a..6193f044 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/dart/InitializerGenerator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/dart/InitializerGenerator.java @@ -43,14 +43,17 @@ public String visit(MessageDef self, Field arg) { @Override public String visit(PrimitiveType self, Field field) { + if (field != null && field.isRepeated()) { + return " = const []"; + } switch (self.getKind()) { - case BOOL: + case BOOL: return " = false"; - + case FLOAT: case DOUBLE: return " = 0.0"; - + case FIXED_32: case FIXED_64: case INT_32: @@ -62,8 +65,8 @@ public String visit(PrimitiveType self, Field field) { case UINT_32: case UINT_64: return " = 0"; - - case BYTES: + + case BYTES: case STRING: return " = \"\""; } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/dart/ReadOperationBuilder.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/dart/ReadOperationBuilder.java index b4d8ed1f..01ea4e73 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/dart/ReadOperationBuilder.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/dart/ReadOperationBuilder.java @@ -123,7 +123,12 @@ public Void visit(MessageDef self, Function statementBuilder) { } else { line("if (!json.tryNull()) {"); { - line(statementBuilder.apply(value)); + line("var value = " + value + ";"); + line("if (value != null) {"); + { + line(statementBuilder.apply("value")); + } + line("}"); } line("}"); } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/dart/TypeNameBuilder.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/dart/TypeNameBuilder.java index 6a3bc079..31c3faa9 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/dart/TypeNameBuilder.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/dart/TypeNameBuilder.java @@ -33,14 +33,17 @@ public String visit(CustomType self, Field arg) { @Override public String visit(PrimitiveType self, Field arg) { + String typeName; switch (self.getKind()) { - case BOOL: - return "bool"; - + case BOOL: + typeName = "bool"; + break; + case FLOAT: case DOUBLE: - return "double"; - + typeName = "double"; + break; + case FIXED_32: case FIXED_64: case INT_32: @@ -51,13 +54,18 @@ public String visit(PrimitiveType self, Field arg) { case SINT_64: case UINT_32: case UINT_64: - return "int"; - - case BYTES: + typeName = "int"; + break; + + case BYTES: case STRING: - return "String"; + typeName = "String"; + break; + + default: + throw new IllegalArgumentException("No such type: " + self); } - throw new IllegalArgumentException("No such type: " + self); + return arg != null && arg.isRepeated() ? "List<" + typeName + ">" : typeName; } @Override diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/ParseException.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/ParseException.java index 390c2bcb..b2260516 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/ParseException.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/ParseException.java @@ -1,5 +1,5 @@ -/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 5.0 */ -/* JavaCCOptions:KEEP_LINE_COL=null */ +/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 7.0 */ +/* JavaCCOptions:KEEP_LINE_COLUMN=true */ package de.haumacher.msgbuf.generator.parser; /** @@ -20,6 +20,11 @@ public class ParseException extends Exception { */ private static final long serialVersionUID = 1L; + /** + * The end of line string for this machine. + */ + protected static String EOL = System.getProperty("line.separator", "\n"); + /** * This constructor is used by the method "generateParseException" * in the generated parser. Calling this constructor generates @@ -60,7 +65,7 @@ public ParseException(String message) { /** * This is the last token that has been consumed successfully. If * this object has been created due to a parse error, the token - * followng this token will (therefore) be the first error token. + * following this token will (therefore) be the first error token. */ public Token currentToken; @@ -88,8 +93,8 @@ public ParseException(String message) { private static String initialise(Token currentToken, int[][] expectedTokenSequences, String[] tokenImage) { - String eol = System.getProperty("line.separator", "\n"); - StringBuffer expected = new StringBuffer(); + + StringBuilder expected = new StringBuilder(); int maxSize = 0; for (int i = 0; i < expectedTokenSequences.length; i++) { if (maxSize < expectedTokenSequences[i].length) { @@ -101,7 +106,7 @@ private static String initialise(Token currentToken, if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { expected.append("..."); } - expected.append(eol).append(" "); + expected.append(EOL).append(" "); } String retval = "Encountered \""; Token tok = currentToken.next; @@ -117,21 +122,26 @@ private static String initialise(Token currentToken, retval += " \""; tok = tok.next; } - retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; - retval += "." + eol; - if (expectedTokenSequences.length == 1) { - retval += "Was expecting:" + eol + " "; + if (currentToken.next != null) { + retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; + } + retval += "." + EOL; + + + if (expectedTokenSequences.length == 0) { + // Nothing to add here } else { - retval += "Was expecting one of:" + eol + " "; + if (expectedTokenSequences.length == 1) { + retval += "Was expecting:" + EOL + " "; + } else { + retval += "Was expecting one of:" + EOL + " "; + } + retval += expected.toString(); } - retval += expected.toString(); + return retval; } - /** - * The end of line string for this machine. - */ - protected String eol = System.getProperty("line.separator", "\n"); /** * Used to convert raw characters to their escaped version @@ -139,13 +149,11 @@ private static String initialise(Token currentToken, * string literal. */ static String add_escapes(String str) { - StringBuffer retval = new StringBuffer(); + StringBuilder retval = new StringBuilder(); char ch; for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { - case 0 : - continue; case '\b': retval.append("\\b"); continue; @@ -184,4 +192,4 @@ static String add_escapes(String str) { } } -/* JavaCC - OriginalChecksum=790c9056a53b6f69ac158c6aec634d2e (do not edit this line) */ +/* JavaCC - OriginalChecksum=b29aa32c2c570384b1b287ad3c4ecb93 (do not edit this line) */ diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/ProtobufParser.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/ProtobufParser.java index 4d5711c0..df08f344 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/ProtobufParser.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/ProtobufParser.java @@ -1,162 +1,193 @@ +/* ProtobufParser.java */ /* Generated By:JavaCC: Do not edit this line. ProtobufParser.java */ package de.haumacher.msgbuf.generator.parser; -import de.haumacher.msgbuf.generator.ast.*; import de.haumacher.msgbuf.generator.common.Util; +import de.haumacher.msgbuf.generator.ast.*; /** * Parser for protobuf definition files.. */ public class ProtobufParser implements ProtobufParserConstants { - final public DefinitionFile file() throws ParseException { - DefinitionFile result = DefinitionFile.create(); + final public DefinitionFile file() throws ParseException {DefinitionFile result = DefinitionFile.create(); QName pkgName; Definition def; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case SYNTAX: - jj_consume_token(SYNTAX); - jj_consume_token(33); + Token t; + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case SYNTAX:{ + t = jj_consume_token(SYNTAX); + jj_consume_token(37); jj_consume_token(STRING); - jj_consume_token(34); + jj_consume_token(38); +result.setComment(Util.stripComment(t)); break; + } default: jj_la1[0] = jj_gen; ; } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case PACKAGE: - jj_consume_token(PACKAGE); + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case PACKAGE:{ + t = jj_consume_token(PACKAGE); +if (result.getComment().isEmpty()) { + result.setComment(Util.stripComment(t)); + } pkgName = qName(); - jj_consume_token(34); - result.setPackage(pkgName); + jj_consume_token(38); +result.setPackage(pkgName); break; + } default: jj_la1[1] = jj_gen; ; } label_1: while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case OPTION: + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case IMPORT:{ ; break; + } default: jj_la1[2] = jj_gen; break label_1; } - optionStatement(result); + jj_consume_token(IMPORT); +Token importPath; + importPath = jj_consume_token(STRING); +result.addImport(de.haumacher.msgbuf.generator.common.Util.stringContent(importPath.image)); + jj_consume_token(38); } label_2: while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case OPTION:{ + ; + break; + } + default: + jj_la1[3] = jj_gen; + break label_2; + } + optionStatement(result); + } + label_3: + while (true) { + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { case MESSAGE: case ENUM: case ABSTRACT: - case 37: + case 41:{ ; break; + } default: - jj_la1[3] = jj_gen; - break label_2; + jj_la1[4] = jj_gen; + break label_3; } def = definition(); - result.addDefinition(def); +result.addDefinition(def); } - {if (true) return result;} +{if ("" != null) return result;} throw new Error("Missing return statement in function"); - } +} final public void optionStatement(WithOptions part) throws ParseException { jj_consume_token(OPTION); optionAssignment(part); - jj_consume_token(34); - } + jj_consume_token(38); +} - final public void optionAssignment(WithOptions part) throws ParseException { - Option option; + final public void optionAssignment(WithOptions part) throws ParseException {Option option; Token t; t = jj_consume_token(NAME); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 33: - jj_consume_token(33); + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case 37:{ + jj_consume_token(37); option = value(); - part.getOptions().put(t.image, option); +part.getOptions().put(t.image, option); break; + } default: - jj_la1[4] = jj_gen; - part.getOptions().put(t.image, Flag.create().setValue(true)); + jj_la1[5] = jj_gen; +part.getOptions().put(t.image, Flag.create().setValue(true)); } - } +} - final public Option value() throws ParseException { - Option result; + final public Option value() throws ParseException {Option result; Token t; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case STRING: + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case STRING:{ t = jj_consume_token(STRING); - result = StringOption.create().setValue(Util.stringContent(t.image)); +result = StringOption.create().setValue(Util.stringContent(t.image)); break; - case NUMBER: + } + case NUMBER:{ t = jj_consume_token(NUMBER); - result = NumberOption.create().setValue(Double.parseDouble(t.image)); +result = NumberOption.create().setValue(Double.parseDouble(t.image)); break; - case TRUE: + } + case TRUE:{ jj_consume_token(TRUE); - result = Flag.create().setValue(true); +result = Flag.create().setValue(true); break; - case FALSE: + } + case FALSE:{ jj_consume_token(FALSE); - result = Flag.create().setValue(false); +result = Flag.create().setValue(false); break; + } default: - jj_la1[5] = jj_gen; + jj_la1[6] = jj_gen; jj_consume_token(-1); throw new ParseException(); } - {if (true) return result;} +{if ("" != null) return result;} throw new Error("Missing return statement in function"); - } +} - final public Definition definition() throws ParseException { - String comment; + final public Definition definition() throws ParseException {String comment; Definition result; WithOptions options; - comment = Util.stripComment(token.next); +comment = Util.stripComment(token.next); options = javaAnnotations(); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { case MESSAGE: - case ABSTRACT: + case ABSTRACT:{ result = message(); break; - case ENUM: + } + case ENUM:{ result = enumeration(); break; + } default: - jj_la1[6] = jj_gen; + jj_la1[7] = jj_gen; jj_consume_token(-1); throw new ParseException(); } - result.setComment(comment); +result.setComment(comment); if (options != null) result.setOptions(options.getOptions()); - {if (true) return result;} + {if ("" != null) return result;} throw new Error("Missing return statement in function"); - } +} - final public DefinitionBase memberDefinition() throws ParseException { - String comment; + final public DefinitionBase memberDefinition() throws ParseException {String comment; DefinitionBase result; WithOptions options; - comment = Util.stripComment(token.next); +comment = Util.stripComment(token.next); options = javaAnnotations(); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { case MESSAGE: - case ABSTRACT: + case ABSTRACT:{ result = message(); break; - case ENUM: + } + case ENUM:{ result = enumeration(); break; + } case MAP: case REPEATED: case TRANSIENT: @@ -165,139 +196,147 @@ final public DefinitionBase memberDefinition() throws ParseException { case INT_TYPE: case LONG_TYPE: case BOOLEAN_TYPE: + case JSON_TYPE: case TYPE: case XNAME: - case NAME: + case NAME:{ result = field(); break; + } default: - jj_la1[7] = jj_gen; + jj_la1[8] = jj_gen; jj_consume_token(-1); throw new ParseException(); } - result.setComment(comment); +result.setComment(comment); if (options != null) result.setOptions(options.getOptions()); - {if (true) return result;} + {if ("" != null) return result;} throw new Error("Missing return statement in function"); - } +} - final public EnumDef enumeration() throws ParseException { - EnumDef result = EnumDef.create(); + final public EnumDef enumeration() throws ParseException {EnumDef result = EnumDef.create(); String name; Constant constant; Token d; d = jj_consume_token(ENUM); name = name(); - jj_consume_token(35); - result.setName(name); + jj_consume_token(39); +result.setName(name); result.setComment(Util.stripComment(d)); - label_3: + label_4: while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case OPTION: + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case OPTION:{ ; break; + } default: - jj_la1[8] = jj_gen; - break label_3; + jj_la1[9] = jj_gen; + break label_4; } optionStatement(result); } - label_4: + label_5: while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { case RESERVED: case TO: case MAX: + case JSON_TYPE: case XNAME: case NAME: - case 37: + case 41:{ ; break; + } default: - jj_la1[9] = jj_gen; - break label_4; + jj_la1[10] = jj_gen; + break label_5; } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { case TO: case MAX: + case JSON_TYPE: case XNAME: case NAME: - case 37: + case 41:{ constant = constant(); - result.addConstant(constant); +result.addConstant(constant); break; - case RESERVED: + } + case RESERVED:{ reserved(); break; + } default: - jj_la1[10] = jj_gen; + jj_la1[11] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } - jj_consume_token(36); - {if (true) return result;} + jj_consume_token(40); +{if ("" != null) return result;} throw new Error("Missing return statement in function"); - } +} - final public Constant constant() throws ParseException { - Constant result = Constant.create(); + final public Constant constant() throws ParseException {Constant result = Constant.create(); String name; Token index; - result.setComment(Util.stripComment(token.next)); +result.setComment(Util.stripComment(token.next)); javaAnnotationsFor(result); name = name(); - result.setName(name); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 33: - jj_consume_token(33); +result.setName(name); + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case 37:{ + jj_consume_token(37); index = jj_consume_token(NUMBER); - result.setIndex(Integer.parseInt(index.image)); +result.setIndex(Integer.parseInt(index.image)); break; + } default: - jj_la1[11] = jj_gen; + jj_la1[12] = jj_gen; ; } partOptions(result); - jj_consume_token(34); - {if (true) return result;} + jj_consume_token(38); +{if ("" != null) return result;} throw new Error("Missing return statement in function"); - } +} - final public MessageDef message() throws ParseException { - MessageDef result = MessageDef.create(); + final public MessageDef message() throws ParseException {MessageDef result = MessageDef.create(); String name; QName generalization; WithOptions def; Field field; Token comment; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case ABSTRACT: + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case ABSTRACT:{ jj_consume_token(ABSTRACT); - result.setAbstract(true); +result.setAbstract(true); break; + } default: - jj_la1[12] = jj_gen; + jj_la1[13] = jj_gen; ; } jj_consume_token(MESSAGE); name = name(); - result.setName(name); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case EXTENDS: +result.setName(name); + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case EXTENDS:{ jj_consume_token(EXTENDS); generalization = qName(); - result.setExtends(generalization); +result.setExtends(generalization); break; + } default: - jj_la1[13] = jj_gen; + jj_la1[14] = jj_gen; ; } - jj_consume_token(35); - label_5: + jj_consume_token(39); + label_6: while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { case MESSAGE: case ENUM: case MAP: @@ -312,20 +351,23 @@ final public MessageDef message() throws ParseException { case INT_TYPE: case LONG_TYPE: case BOOLEAN_TYPE: + case JSON_TYPE: case TYPE: case XNAME: case NAME: - case 37: + case 41:{ ; break; + } default: - jj_la1[14] = jj_gen; - break label_5; + jj_la1[15] = jj_gen; + break label_6; } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case OPTION: + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case OPTION:{ optionStatement(result); break; + } case MESSAGE: case ENUM: case MAP: @@ -337,364 +379,423 @@ final public MessageDef message() throws ParseException { case INT_TYPE: case LONG_TYPE: case BOOLEAN_TYPE: + case JSON_TYPE: case TYPE: case XNAME: case NAME: - case 37: + case 41:{ def = memberDefinition(); - if (def instanceof Field) { +if (def instanceof Field) { result.addField((Field) def); } else { result.addDefinition((Definition) def); } break; - case ONEOF: + } + case ONEOF:{ oneof(); break; - case RESERVED: + } + case RESERVED:{ reserved(); break; + } default: - jj_la1[15] = jj_gen; + jj_la1[16] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } - jj_consume_token(36); - {if (true) return result;} + jj_consume_token(40); +{if ("" != null) return result;} throw new Error("Missing return statement in function"); - } +} - final public Field field() throws ParseException { - Field result = Field.create(); + final public Field field() throws ParseException {Field result = Field.create(); Type type; String name; - Token index; + Token def; Token comment; Option option; Token optionName; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case TRANSIENT: + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case TRANSIENT:{ jj_consume_token(TRANSIENT); - result.setTransient(true); +result.setTransient(true); break; + } default: - jj_la1[16] = jj_gen; + jj_la1[17] = jj_gen; ; } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case REPEATED: + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case REPEATED:{ jj_consume_token(REPEATED); - result.setRepeated(true); +result.setRepeated(true); break; + } default: - jj_la1[17] = jj_gen; + jj_la1[18] = jj_gen; ; } type = type(); - result.setType(type); +result.setType(type); name = name(); - result.setName(name); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 33: - jj_consume_token(33); - index = jj_consume_token(NUMBER); - result.setIndex(Integer.parseInt(index.image)); +result.setName(name); + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case 37:{ + jj_consume_token(37); + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case NUMBER:{ + def = jj_consume_token(NUMBER); + break; + } + case TRUE:{ + def = jj_consume_token(TRUE); + break; + } + case FALSE:{ + def = jj_consume_token(FALSE); + break; + } + case STRING:{ + def = jj_consume_token(STRING); + break; + } + case NULL:{ + def = jj_consume_token(NULL); + break; + } + default: + jj_la1[19] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } +result.setDefaultValue(def.image); break; + } default: - jj_la1[18] = jj_gen; + jj_la1[20] = jj_gen; ; } partOptions(result); - jj_consume_token(34); - {if (true) return result;} + jj_consume_token(38); +{if ("" != null) return result;} throw new Error("Missing return statement in function"); - } +} - final public WithOptions javaAnnotations() throws ParseException { - WithOptions result; + final public WithOptions javaAnnotations() throws ParseException {WithOptions result; result = javaAnnotationsFor(null); - {if (true) return result;} +{if ("" != null) return result;} throw new Error("Missing return statement in function"); - } +} - final public WithOptions javaAnnotationsFor(WithOptions result) throws ParseException { - Token optionName; + final public WithOptions javaAnnotationsFor(WithOptions result) throws ParseException {Token optionName; Option option; - label_6: + label_7: while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 37: + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case 41:{ ; break; + } default: - jj_la1[19] = jj_gen; - break label_6; + jj_la1[21] = jj_gen; + break label_7; } - if (result == null) result = OptionContainer.create(); - jj_consume_token(37); +if (result == null) result = OptionContainer.create(); + jj_consume_token(41); optionName = jj_consume_token(NAME); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 38: - jj_consume_token(38); + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case 42:{ + jj_consume_token(42); option = value(); - jj_consume_token(39); - result.getOptions().put(optionName.image, option); + jj_consume_token(43); +result.getOptions().put(optionName.image, option); break; + } default: - jj_la1[20] = jj_gen; - result.getOptions().put(optionName.image, Flag.create().setValue(true)); + jj_la1[22] = jj_gen; +result.getOptions().put(optionName.image, Flag.create().setValue(true)); } } - {if (true) return result;} +{if ("" != null) return result;} throw new Error("Missing return statement in function"); - } +} final public void partOptions(Part part) throws ParseException { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 40: - jj_consume_token(40); + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case 44:{ + jj_consume_token(44); optionAssignment(part); - label_7: + label_8: while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 41: + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case 45:{ ; break; + } default: - jj_la1[21] = jj_gen; - break label_7; + jj_la1[23] = jj_gen; + break label_8; } - jj_consume_token(41); + jj_consume_token(45); optionAssignment(part); } - jj_consume_token(42); + jj_consume_token(46); break; + } default: - jj_la1[22] = jj_gen; + jj_la1[24] = jj_gen; ; } - } +} final public void reserved() throws ParseException { jj_consume_token(RESERVED); reservation(); - label_8: + label_9: while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 41: + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case 45:{ ; break; + } default: - jj_la1[23] = jj_gen; - break label_8; + jj_la1[25] = jj_gen; + break label_9; } - jj_consume_token(41); + jj_consume_token(45); reservation(); } - jj_consume_token(34); - } + jj_consume_token(38); +} final public void reservation() throws ParseException { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case NUMBER: + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case NUMBER:{ jj_consume_token(NUMBER); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case TO: + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case TO:{ jj_consume_token(TO); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case NUMBER: + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case NUMBER:{ jj_consume_token(NUMBER); break; - case MAX: + } + case MAX:{ jj_consume_token(MAX); break; + } default: - jj_la1[24] = jj_gen; + jj_la1[26] = jj_gen; jj_consume_token(-1); throw new ParseException(); } break; + } default: - jj_la1[25] = jj_gen; + jj_la1[27] = jj_gen; ; } break; - case STRING: + } + case STRING:{ jj_consume_token(STRING); break; + } default: - jj_la1[26] = jj_gen; + jj_la1[28] = jj_gen; jj_consume_token(-1); throw new ParseException(); } - } +} final public void oneof() throws ParseException { jj_consume_token(ONEOF); jj_consume_token(NAME); - jj_consume_token(35); - label_9: + jj_consume_token(39); + label_10: while (true) { type(); jj_consume_token(NAME); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 33: - jj_consume_token(33); + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case 37:{ + jj_consume_token(37); jj_consume_token(NUMBER); break; + } default: - jj_la1[27] = jj_gen; + jj_la1[29] = jj_gen; ; } - jj_consume_token(34); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + jj_consume_token(38); + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { case MAP: case TO: case MAX: case INT_TYPE: case LONG_TYPE: case BOOLEAN_TYPE: + case JSON_TYPE: case TYPE: case XNAME: - case NAME: + case NAME:{ ; break; + } default: - jj_la1[28] = jj_gen; - break label_9; + jj_la1[30] = jj_gen; + break label_10; } } - jj_consume_token(36); - } + jj_consume_token(40); +} - final public Type type() throws ParseException { - Type result; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + final public Type type() throws ParseException {Type result; + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { case INT_TYPE: case LONG_TYPE: case BOOLEAN_TYPE: - case TYPE: + case JSON_TYPE: + case TYPE:{ result = primitiveType(); break; + } case TO: case MAX: case XNAME: - case NAME: + case NAME:{ result = customType(); break; - case MAP: + } + case MAP:{ result = map(); break; + } default: - jj_la1[29] = jj_gen; + jj_la1[31] = jj_gen; jj_consume_token(-1); throw new ParseException(); } - {if (true) return result;} +{if ("" != null) return result;} throw new Error("Missing return statement in function"); - } +} - final public PrimitiveType primitiveType() throws ParseException { - Token t; + final public PrimitiveType primitiveType() throws ParseException {Token t; PrimitiveType result; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case TYPE: + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case TYPE:{ t = jj_consume_token(TYPE); - result = PrimitiveType.create().setKind(PrimitiveType.Kind.valueOfProtocol(t.image.toUpperCase())); +result = PrimitiveType.create().setKind(PrimitiveType.Kind.valueOfProtocol(t.image.toUpperCase())); break; - case INT_TYPE: + } + case INT_TYPE:{ t = jj_consume_token(INT_TYPE); - result = PrimitiveType.create().setKind(PrimitiveType.Kind.INT_32); +result = PrimitiveType.create().setKind(PrimitiveType.Kind.INT_32); break; - case LONG_TYPE: + } + case LONG_TYPE:{ t = jj_consume_token(LONG_TYPE); - result = PrimitiveType.create().setKind(PrimitiveType.Kind.INT_64); +result = PrimitiveType.create().setKind(PrimitiveType.Kind.INT_64); break; - case BOOLEAN_TYPE: + } + case BOOLEAN_TYPE:{ t = jj_consume_token(BOOLEAN_TYPE); - result = PrimitiveType.create().setKind(PrimitiveType.Kind.BOOL); +result = PrimitiveType.create().setKind(PrimitiveType.Kind.BOOL); + break; + } + case JSON_TYPE:{ + t = jj_consume_token(JSON_TYPE); +result = PrimitiveType.create().setKind(PrimitiveType.Kind.JSON); break; + } default: - jj_la1[30] = jj_gen; + jj_la1[32] = jj_gen; jj_consume_token(-1); throw new ParseException(); } - {if (true) return result;} +{if ("" != null) return result;} throw new Error("Missing return statement in function"); - } +} - final public CustomType customType() throws ParseException { - QName name; + final public CustomType customType() throws ParseException {QName name; name = qName(); - {if (true) return CustomType.create().setName(name);} +{if ("" != null) return CustomType.create().setName(name);} throw new Error("Missing return statement in function"); - } +} - final public MapType map() throws ParseException { - Type keyType; + final public MapType map() throws ParseException {Type keyType; Type valueType; jj_consume_token(MAP); - jj_consume_token(43); + jj_consume_token(47); keyType = type(); - jj_consume_token(41); + jj_consume_token(45); valueType = type(); - jj_consume_token(44); - {if (true) return MapType.create().setKeyType(keyType).setValueType(valueType);} + jj_consume_token(48); +{if ("" != null) return MapType.create().setKeyType(keyType).setValueType(valueType);} throw new Error("Missing return statement in function"); - } +} - final public QName qName() throws ParseException { - QName result = QName.create(); + final public QName qName() throws ParseException {QName result = QName.create(); String name; name = name(); - result.addName(name); - label_10: +result.addName(name); + label_11: while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 45: + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case 49:{ ; break; + } default: - jj_la1[31] = jj_gen; - break label_10; + jj_la1[33] = jj_gen; + break label_11; } - jj_consume_token(45); + jj_consume_token(49); name = name(); - result.addName(name); +result.addName(name); } - {if (true) return result;} +{if ("" != null) return result;} throw new Error("Missing return statement in function"); - } +} - final public String name() throws ParseException { - Token t; + final public String name() throws ParseException {Token t; String result; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case NAME: + switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) { + case NAME:{ t = jj_consume_token(NAME); - result = t.image; +result = t.image; break; - case TO: + } + case TO:{ t = jj_consume_token(TO); - result = t.image; +result = t.image; break; - case MAX: + } + case MAX:{ t = jj_consume_token(MAX); - result = t.image; +result = t.image; break; - case XNAME: + } + case JSON_TYPE:{ + t = jj_consume_token(JSON_TYPE); +result = t.image; + break; + } + case XNAME:{ t = jj_consume_token(XNAME); - result = t.image.substring(1, t.image.length() - 1); +result = t.image.substring(1, t.image.length() - 1); break; + } default: - jj_la1[32] = jj_gen; + jj_la1[34] = jj_gen; jj_consume_token(-1); throw new ParseException(); } - {if (true) return result;} +{if ("" != null) return result;} throw new Error("Missing return statement in function"); - } +} /** Generated Token Manager. */ public ProtobufParserTokenManager token_source; @@ -705,125 +806,133 @@ final public String name() throws ParseException { public Token jj_nt; private int jj_ntk; private int jj_gen; - final private int[] jj_la1 = new int[33]; + final private int[] jj_la1 = new int[35]; static private int[] jj_la1_0; static private int[] jj_la1_1; static { - jj_la1_init_0(); - jj_la1_init_1(); - } - private static void jj_la1_init_0() { - jj_la1_0 = new int[] {0x200,0x100,0x10000,0x40c00,0x0,0x30c00000,0x40c00,0x4f34dc00,0x10000,0x40380000,0x40380000,0x0,0x40000,0x20000,0x4f3dfc00,0x4f3dfc00,0x8000,0x4000,0x0,0x0,0x0,0x0,0x0,0x0,0x10200000,0x100000,0x30000000,0x0,0x4f301000,0x4f301000,0xf000000,0x0,0x40300000,}; - } - private static void jj_la1_init_1() { - jj_la1_1 = new int[] {0x0,0x0,0x0,0x20,0x2,0x0,0x0,0x1,0x0,0x21,0x21,0x2,0x0,0x0,0x21,0x21,0x0,0x0,0x2,0x20,0x40,0x200,0x100,0x200,0x0,0x0,0x0,0x2,0x1,0x1,0x0,0x2000,0x1,}; - } + jj_la1_init_0(); + jj_la1_init_1(); + } + private static void jj_la1_init_0() { + jj_la1_0 = new int[] {0x400,0x100,0x200,0x20000,0x81800,0x0,0x1800000,0x81800,0x7c69b800,0x20000,0x20700000,0x20700000,0x0,0x80000,0x40000,0x7c7bf800,0x7c7bf800,0x10000,0x8000,0x3800000,0x0,0x0,0x0,0x0,0x0,0x0,0x400000,0x200000,0x0,0x0,0x7c602000,0x7c602000,0x7c000000,0x0,0x20600000,}; + } + private static void jj_la1_init_1() { + jj_la1_1 = new int[] {0x0,0x0,0x0,0x0,0x200,0x20,0x3,0x0,0x14,0x0,0x214,0x214,0x20,0x0,0x0,0x214,0x214,0x0,0x0,0x3,0x20,0x200,0x400,0x2000,0x1000,0x2000,0x1,0x0,0x3,0x20,0x14,0x14,0x0,0x20000,0x14,}; + } /** Constructor with InputStream. */ public ProtobufParser(java.io.InputStream stream) { - this(stream, null); + this(stream, null); } /** Constructor with InputStream and supplied encoding */ public ProtobufParser(java.io.InputStream stream, String encoding) { - try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } - token_source = new ProtobufParserTokenManager(jj_input_stream); - token = new Token(); - jj_ntk = -1; - jj_gen = 0; - for (int i = 0; i < 33; i++) jj_la1[i] = -1; + try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } + token_source = new ProtobufParserTokenManager(jj_input_stream); + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 35; i++) jj_la1[i] = -1; } /** Reinitialise. */ public void ReInit(java.io.InputStream stream) { - ReInit(stream, null); + ReInit(stream, null); } /** Reinitialise. */ public void ReInit(java.io.InputStream stream, String encoding) { - try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } - token_source.ReInit(jj_input_stream); - token = new Token(); - jj_ntk = -1; - jj_gen = 0; - for (int i = 0; i < 33; i++) jj_la1[i] = -1; + try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } + token_source.ReInit(jj_input_stream); + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 35; i++) jj_la1[i] = -1; } /** Constructor. */ public ProtobufParser(java.io.Reader stream) { - jj_input_stream = new SimpleCharStream(stream, 1, 1); - token_source = new ProtobufParserTokenManager(jj_input_stream); - token = new Token(); - jj_ntk = -1; - jj_gen = 0; - for (int i = 0; i < 33; i++) jj_la1[i] = -1; + jj_input_stream = new SimpleCharStream(stream, 1, 1); + token_source = new ProtobufParserTokenManager(jj_input_stream); + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 35; i++) jj_la1[i] = -1; } /** Reinitialise. */ public void ReInit(java.io.Reader stream) { - jj_input_stream.ReInit(stream, 1, 1); - token_source.ReInit(jj_input_stream); - token = new Token(); - jj_ntk = -1; - jj_gen = 0; - for (int i = 0; i < 33; i++) jj_la1[i] = -1; + if (jj_input_stream == null) { + jj_input_stream = new SimpleCharStream(stream, 1, 1); + } else { + jj_input_stream.ReInit(stream, 1, 1); + } + if (token_source == null) { + token_source = new ProtobufParserTokenManager(jj_input_stream); + } + + token_source.ReInit(jj_input_stream); + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 35; i++) jj_la1[i] = -1; } /** Constructor with generated Token Manager. */ public ProtobufParser(ProtobufParserTokenManager tm) { - token_source = tm; - token = new Token(); - jj_ntk = -1; - jj_gen = 0; - for (int i = 0; i < 33; i++) jj_la1[i] = -1; + token_source = tm; + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 35; i++) jj_la1[i] = -1; } /** Reinitialise. */ public void ReInit(ProtobufParserTokenManager tm) { - token_source = tm; - token = new Token(); - jj_ntk = -1; - jj_gen = 0; - for (int i = 0; i < 33; i++) jj_la1[i] = -1; + token_source = tm; + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 35; i++) jj_la1[i] = -1; } private Token jj_consume_token(int kind) throws ParseException { - Token oldToken; - if ((oldToken = token).next != null) token = token.next; - else token = token.next = token_source.getNextToken(); - jj_ntk = -1; - if (token.kind == kind) { - jj_gen++; - return token; - } - token = oldToken; - jj_kind = kind; - throw generateParseException(); + Token oldToken; + if ((oldToken = token).next != null) token = token.next; + else token = token.next = token_source.getNextToken(); + jj_ntk = -1; + if (token.kind == kind) { + jj_gen++; + return token; + } + token = oldToken; + jj_kind = kind; + throw generateParseException(); } /** Get the next Token. */ final public Token getNextToken() { - if (token.next != null) token = token.next; - else token = token.next = token_source.getNextToken(); - jj_ntk = -1; - jj_gen++; - return token; + if (token.next != null) token = token.next; + else token = token.next = token_source.getNextToken(); + jj_ntk = -1; + jj_gen++; + return token; } /** Get the specific Token. */ final public Token getToken(int index) { - Token t = token; - for (int i = 0; i < index; i++) { - if (t.next != null) t = t.next; - else t = t.next = token_source.getNextToken(); - } - return t; + Token t = token; + for (int i = 0; i < index; i++) { + if (t.next != null) t = t.next; + else t = t.next = token_source.getNextToken(); + } + return t; } - private int jj_ntk() { - if ((jj_nt=token.next) == null) - return (jj_ntk = (token.next=token_source.getNextToken()).kind); - else - return (jj_ntk = jj_nt.kind); + private int jj_ntk_f() { + if ((jj_nt=token.next) == null) + return (jj_ntk = (token.next=token_source.getNextToken()).kind); + else + return (jj_ntk = jj_nt.kind); } private java.util.List jj_expentries = new java.util.ArrayList(); @@ -832,36 +941,43 @@ private int jj_ntk() { /** Generate ParseException. */ public ParseException generateParseException() { - jj_expentries.clear(); - boolean[] la1tokens = new boolean[46]; - if (jj_kind >= 0) { - la1tokens[jj_kind] = true; - jj_kind = -1; - } - for (int i = 0; i < 33; i++) { - if (jj_la1[i] == jj_gen) { - for (int j = 0; j < 32; j++) { - if ((jj_la1_0[i] & (1<= 0) { + la1tokens[jj_kind] = true; + jj_kind = -1; + } + for (int i = 0; i < 35; i++) { + if (jj_la1[i] == jj_gen) { + for (int j = 0; j < 32; j++) { + if ((jj_la1_0[i] & (1<", "", "\"package\"", + "\"import\"", "\"syntax\"", "\"message\"", "\"enum\"", @@ -104,10 +113,13 @@ public interface ProtobufParserConstants { "\"max\"", "\"true\"", "\"false\"", + "\"null\"", "\"int\"", "\"long\"", "\"boolean\"", + "\"json\"", "", + "", "", "", "", diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/ProtobufParserTokenManager.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/ProtobufParserTokenManager.java index b8876ed9..0193045f 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/ProtobufParserTokenManager.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/ProtobufParserTokenManager.java @@ -1,149 +1,148 @@ +/* ProtobufParserTokenManager.java */ /* Generated By:JavaCC: Do not edit this line. ProtobufParserTokenManager.java */ package de.haumacher.msgbuf.generator.parser; -import de.haumacher.msgbuf.generator.ast.*; import de.haumacher.msgbuf.generator.common.Util; +import de.haumacher.msgbuf.generator.ast.*; /** Token Manager. */ -public class ProtobufParserTokenManager implements ProtobufParserConstants -{ +@SuppressWarnings ("unused") +public class ProtobufParserTokenManager implements ProtobufParserConstants { /** Debug output. */ public java.io.PrintStream debugStream = System.out; /** Set debug output. */ public void setDebugStream(java.io.PrintStream ds) { debugStream = ds; } -private final int jjStopStringLiteralDfa_0(int pos, long active0) -{ +private final int jjStopStringLiteralDfa_0(int pos, long active0){ switch (pos) { case 0: - if ((active0 & 0x800000L) != 0L) + if ((active0 & 0x10000000L) != 0L) { - jjmatchedKind = 32; - return 35; + jjmatchedKind = 36; + return 98; } - if ((active0 & 0x27ffd00L) != 0L) + if ((active0 & 0x4000200L) != 0L) { - jjmatchedKind = 32; - return 30; + jjmatchedKind = 36; + return 56; } if ((active0 & 0x1000000L) != 0L) { - jjmatchedKind = 32; - return 51; + jjmatchedKind = 36; + return 40; } - if ((active0 & 0x200L) != 0L) + if ((active0 & 0x400L) != 0L) { - jjmatchedKind = 32; - return 68; + jjmatchedKind = 36; + return 73; } - if ((active0 & 0x4000000L) != 0L) + if ((active0 & 0x2afff900L) != 0L) { - jjmatchedKind = 32; - return 93; + jjmatchedKind = 36; + return 35; } return -1; case 1: + if ((active0 & 0x200000L) != 0L) + return 35; if ((active0 & 0x4000000L) != 0L) { - jjmatchedKind = 32; + jjmatchedKind = 36; jjmatchedPos = 1; - return 92; + return 55; } - if ((active0 & 0x1000000L) != 0L) + if ((active0 & 0x10000000L) != 0L) { - jjmatchedKind = 32; + jjmatchedKind = 36; jjmatchedPos = 1; - return 50; + return 97; } - if ((active0 & 0x2efff00L) != 0L) + if ((active0 & 0x2bdfff00L) != 0L) { - jjmatchedKind = 32; + jjmatchedKind = 36; jjmatchedPos = 1; - return 30; + return 35; } - if ((active0 & 0x100000L) != 0L) - return 30; return -1; case 2: - if ((active0 & 0x1000000L) != 0L) - return 49; - if ((active0 & 0x2cfef00L) != 0L) + if ((active0 & 0x2b9fdf00L) != 0L) { - jjmatchedKind = 32; + jjmatchedKind = 36; jjmatchedPos = 2; - return 30; + return 35; } - if ((active0 & 0x201000L) != 0L) - return 30; - if ((active0 & 0x4000000L) != 0L) + if ((active0 & 0x10000000L) != 0L) { - jjmatchedKind = 32; + jjmatchedKind = 36; jjmatchedPos = 2; - return 91; + return 96; } + if ((active0 & 0x402000L) != 0L) + return 35; + if ((active0 & 0x4000000L) != 0L) + return 54; return -1; case 3: - if ((active0 & 0x8fe700L) != 0L) + if ((active0 & 0x2a801000L) != 0L) + return 35; + if ((active0 & 0x11fcf00L) != 0L) { - jjmatchedKind = 32; + jjmatchedKind = 36; jjmatchedPos = 3; - return 30; + return 35; } - if ((active0 & 0x4000000L) != 0L) + if ((active0 & 0x10000000L) != 0L) { - jjmatchedKind = 27; + jjmatchedKind = 30; jjmatchedPos = 3; - return 30; + return 35; } - if ((active0 & 0x2400800L) != 0L) - return 30; return -1; case 4: - if ((active0 & 0x40fc700L) != 0L) + if ((active0 & 0x1004000L) != 0L) + return 35; + if ((active0 & 0x101f8f00L) != 0L) { - jjmatchedKind = 32; + jjmatchedKind = 36; jjmatchedPos = 4; - return 30; + return 35; } - if ((active0 & 0x802000L) != 0L) - return 30; return -1; case 5: - if ((active0 & 0x40ec500L) != 0L) + if ((active0 & 0x101d8900L) != 0L) { - jjmatchedKind = 32; + jjmatchedKind = 36; jjmatchedPos = 5; - return 30; + return 35; } - if ((active0 & 0x10200L) != 0L) - return 30; + if ((active0 & 0x20600L) != 0L) + return 35; return -1; case 6: - if ((active0 & 0x4020500L) != 0L) - return 30; - if ((active0 & 0xcc000L) != 0L) + if ((active0 & 0x198000L) != 0L) { - jjmatchedKind = 32; + jjmatchedKind = 36; jjmatchedPos = 6; - return 30; + return 35; } + if ((active0 & 0x10040900L) != 0L) + return 35; return -1; case 7: - if ((active0 & 0x8000L) != 0L) + if ((active0 & 0x188000L) != 0L) + return 35; + if ((active0 & 0x10000L) != 0L) { - jjmatchedKind = 32; + jjmatchedKind = 36; jjmatchedPos = 7; - return 30; + return 35; } - if ((active0 & 0xc4000L) != 0L) - return 30; return -1; default : return -1; } } -private final int jjStartNfa_0(int pos, long active0) -{ +private final int jjStartNfa_0(int pos, long active0){ return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0), pos + 1); } private int jjStopAtPos(int pos, int kind) @@ -152,66 +151,68 @@ private int jjStopAtPos(int pos, int kind) jjmatchedPos = pos; return pos + 1; } -private int jjMoveStringLiteralDfa0_0() -{ +private int jjMoveStringLiteralDfa0_0(){ switch(curChar) { case 40: - return jjStopAtPos(0, 38); + return jjStopAtPos(0, 42); case 41: - return jjStopAtPos(0, 39); + return jjStopAtPos(0, 43); case 44: - return jjStopAtPos(0, 41); - case 46: return jjStopAtPos(0, 45); + case 46: + return jjStopAtPos(0, 49); case 59: - return jjStopAtPos(0, 34); + return jjStopAtPos(0, 38); case 60: - return jjStopAtPos(0, 43); + return jjStopAtPos(0, 47); case 61: - return jjStopAtPos(0, 33); + return jjStopAtPos(0, 37); case 62: - return jjStopAtPos(0, 44); + return jjStopAtPos(0, 48); case 64: - return jjStopAtPos(0, 37); + return jjStopAtPos(0, 41); case 91: - return jjStopAtPos(0, 40); + return jjStopAtPos(0, 44); case 93: - return jjStopAtPos(0, 42); + return jjStopAtPos(0, 46); case 97: - return jjMoveStringLiteralDfa1_0(0x40000L); + return jjMoveStringLiteralDfa1_0(0x80000L); case 98: - return jjMoveStringLiteralDfa1_0(0x4000000L); + return jjMoveStringLiteralDfa1_0(0x10000000L); case 101: - return jjMoveStringLiteralDfa1_0(0x20800L); + return jjMoveStringLiteralDfa1_0(0x41000L); case 102: - return jjMoveStringLiteralDfa1_0(0x800000L); - case 105: return jjMoveStringLiteralDfa1_0(0x1000000L); + case 105: + return jjMoveStringLiteralDfa1_0(0x4000200L); + case 106: + return jjMoveStringLiteralDfa1_0(0x20000000L); case 108: - return jjMoveStringLiteralDfa1_0(0x2000000L); + return jjMoveStringLiteralDfa1_0(0x8000000L); case 109: - return jjMoveStringLiteralDfa1_0(0x201400L); + return jjMoveStringLiteralDfa1_0(0x402800L); + case 110: + return jjMoveStringLiteralDfa1_0(0x2000000L); case 111: - return jjMoveStringLiteralDfa1_0(0x12000L); + return jjMoveStringLiteralDfa1_0(0x24000L); case 112: return jjMoveStringLiteralDfa1_0(0x100L); case 114: - return jjMoveStringLiteralDfa1_0(0x84000L); + return jjMoveStringLiteralDfa1_0(0x108000L); case 115: - return jjMoveStringLiteralDfa1_0(0x200L); + return jjMoveStringLiteralDfa1_0(0x400L); case 116: - return jjMoveStringLiteralDfa1_0(0x508000L); + return jjMoveStringLiteralDfa1_0(0xa10000L); case 123: - return jjStopAtPos(0, 35); + return jjStopAtPos(0, 39); case 125: - return jjStopAtPos(0, 36); + return jjStopAtPos(0, 40); default : return jjMoveNfa_0(5, 0); } } -private int jjMoveStringLiteralDfa1_0(long active0) -{ +private int jjMoveStringLiteralDfa1_0(long active0){ try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(0, active0); @@ -220,32 +221,37 @@ private int jjMoveStringLiteralDfa1_0(long active0) switch(curChar) { case 97: - return jjMoveStringLiteralDfa2_0(active0, 0xa01100L); + return jjMoveStringLiteralDfa2_0(active0, 0x1402100L); case 98: - return jjMoveStringLiteralDfa2_0(active0, 0x40000L); + return jjMoveStringLiteralDfa2_0(active0, 0x80000L); case 101: - return jjMoveStringLiteralDfa2_0(active0, 0x84400L); + return jjMoveStringLiteralDfa2_0(active0, 0x108800L); + case 109: + return jjMoveStringLiteralDfa2_0(active0, 0x200L); case 110: - return jjMoveStringLiteralDfa2_0(active0, 0x1002800L); + return jjMoveStringLiteralDfa2_0(active0, 0x4005000L); case 111: - if ((active0 & 0x100000L) != 0L) - return jjStartNfaWithStates_0(1, 20, 30); - return jjMoveStringLiteralDfa2_0(active0, 0x6000000L); + if ((active0 & 0x200000L) != 0L) + return jjStartNfaWithStates_0(1, 21, 35); + return jjMoveStringLiteralDfa2_0(active0, 0x18000000L); case 112: - return jjMoveStringLiteralDfa2_0(active0, 0x10000L); + return jjMoveStringLiteralDfa2_0(active0, 0x20000L); case 114: - return jjMoveStringLiteralDfa2_0(active0, 0x408000L); + return jjMoveStringLiteralDfa2_0(active0, 0x810000L); + case 115: + return jjMoveStringLiteralDfa2_0(active0, 0x20000000L); + case 117: + return jjMoveStringLiteralDfa2_0(active0, 0x2000000L); case 120: - return jjMoveStringLiteralDfa2_0(active0, 0x20000L); + return jjMoveStringLiteralDfa2_0(active0, 0x40000L); case 121: - return jjMoveStringLiteralDfa2_0(active0, 0x200L); + return jjMoveStringLiteralDfa2_0(active0, 0x400L); default : break; } return jjStartNfa_0(0, active0); } -private int jjMoveStringLiteralDfa2_0(long old0, long active0) -{ +private int jjMoveStringLiteralDfa2_0(long old0, long active0){ if (((active0 &= old0)) == 0L) return jjStartNfa_0(0, old0); try { curChar = input_stream.readChar(); } @@ -256,40 +262,39 @@ private int jjMoveStringLiteralDfa2_0(long old0, long active0) switch(curChar) { case 97: - return jjMoveStringLiteralDfa3_0(active0, 0x8000L); + return jjMoveStringLiteralDfa3_0(active0, 0x10000L); case 99: return jjMoveStringLiteralDfa3_0(active0, 0x100L); case 101: - return jjMoveStringLiteralDfa3_0(active0, 0x2000L); + return jjMoveStringLiteralDfa3_0(active0, 0x4000L); case 108: - return jjMoveStringLiteralDfa3_0(active0, 0x800000L); + return jjMoveStringLiteralDfa3_0(active0, 0x3000000L); case 110: - return jjMoveStringLiteralDfa3_0(active0, 0x2000200L); + return jjMoveStringLiteralDfa3_0(active0, 0x8000400L); case 111: - return jjMoveStringLiteralDfa3_0(active0, 0x4000000L); + return jjMoveStringLiteralDfa3_0(active0, 0x30000000L); case 112: - if ((active0 & 0x1000L) != 0L) - return jjStartNfaWithStates_0(2, 12, 30); - return jjMoveStringLiteralDfa3_0(active0, 0x4000L); + if ((active0 & 0x2000L) != 0L) + return jjStartNfaWithStates_0(2, 13, 35); + return jjMoveStringLiteralDfa3_0(active0, 0x8200L); case 115: - return jjMoveStringLiteralDfa3_0(active0, 0xc0400L); + return jjMoveStringLiteralDfa3_0(active0, 0x180800L); case 116: - if ((active0 & 0x1000000L) != 0L) - return jjStartNfaWithStates_0(2, 24, 49); - return jjMoveStringLiteralDfa3_0(active0, 0x30000L); + if ((active0 & 0x4000000L) != 0L) + return jjStartNfaWithStates_0(2, 26, 54); + return jjMoveStringLiteralDfa3_0(active0, 0x60000L); case 117: - return jjMoveStringLiteralDfa3_0(active0, 0x400800L); + return jjMoveStringLiteralDfa3_0(active0, 0x801000L); case 120: - if ((active0 & 0x200000L) != 0L) - return jjStartNfaWithStates_0(2, 21, 30); + if ((active0 & 0x400000L) != 0L) + return jjStartNfaWithStates_0(2, 22, 35); break; default : break; } return jjStartNfa_0(1, active0); } -private int jjMoveStringLiteralDfa3_0(long old0, long active0) -{ +private int jjMoveStringLiteralDfa3_0(long old0, long active0){ if (((active0 &= old0)) == 0L) return jjStartNfa_0(1, old0); try { curChar = input_stream.readChar(); } @@ -300,38 +305,41 @@ private int jjMoveStringLiteralDfa3_0(long old0, long active0) switch(curChar) { case 101: - if ((active0 & 0x400000L) != 0L) - return jjStartNfaWithStates_0(3, 22, 30); - return jjMoveStringLiteralDfa4_0(active0, 0xa4000L); + if ((active0 & 0x800000L) != 0L) + return jjStartNfaWithStates_0(3, 23, 35); + return jjMoveStringLiteralDfa4_0(active0, 0x148000L); case 103: - if ((active0 & 0x2000000L) != 0L) - return jjStartNfaWithStates_0(3, 25, 30); + if ((active0 & 0x8000000L) != 0L) + return jjStartNfaWithStates_0(3, 27, 35); break; case 105: - return jjMoveStringLiteralDfa4_0(active0, 0x10000L); + return jjMoveStringLiteralDfa4_0(active0, 0x20000L); case 107: return jjMoveStringLiteralDfa4_0(active0, 0x100L); case 108: - return jjMoveStringLiteralDfa4_0(active0, 0x4000000L); + if ((active0 & 0x2000000L) != 0L) + return jjStartNfaWithStates_0(3, 25, 35); + return jjMoveStringLiteralDfa4_0(active0, 0x10000000L); case 109: - if ((active0 & 0x800L) != 0L) - return jjStartNfaWithStates_0(3, 11, 30); + if ((active0 & 0x1000L) != 0L) + return jjStartNfaWithStates_0(3, 12, 35); break; case 110: - return jjMoveStringLiteralDfa4_0(active0, 0x8000L); + if ((active0 & 0x20000000L) != 0L) + return jjStartNfaWithStates_0(3, 29, 35); + return jjMoveStringLiteralDfa4_0(active0, 0x10000L); case 111: - return jjMoveStringLiteralDfa4_0(active0, 0x2000L); + return jjMoveStringLiteralDfa4_0(active0, 0x4200L); case 115: - return jjMoveStringLiteralDfa4_0(active0, 0x800400L); + return jjMoveStringLiteralDfa4_0(active0, 0x1000800L); case 116: - return jjMoveStringLiteralDfa4_0(active0, 0x40200L); + return jjMoveStringLiteralDfa4_0(active0, 0x80400L); default : break; } return jjStartNfa_0(2, active0); } -private int jjMoveStringLiteralDfa4_0(long old0, long active0) -{ +private int jjMoveStringLiteralDfa4_0(long old0, long active0){ if (((active0 &= old0)) == 0L) return jjStartNfa_0(2, old0); try { curChar = input_stream.readChar(); } @@ -342,30 +350,29 @@ private int jjMoveStringLiteralDfa4_0(long old0, long active0) switch(curChar) { case 97: - return jjMoveStringLiteralDfa5_0(active0, 0x4700L); + return jjMoveStringLiteralDfa5_0(active0, 0x8d00L); case 101: - if ((active0 & 0x800000L) != 0L) - return jjStartNfaWithStates_0(4, 23, 30); - return jjMoveStringLiteralDfa5_0(active0, 0x4000000L); + if ((active0 & 0x1000000L) != 0L) + return jjStartNfaWithStates_0(4, 24, 35); + return jjMoveStringLiteralDfa5_0(active0, 0x10000000L); case 102: - if ((active0 & 0x2000L) != 0L) - return jjStartNfaWithStates_0(4, 13, 30); + if ((active0 & 0x4000L) != 0L) + return jjStartNfaWithStates_0(4, 14, 35); break; case 110: - return jjMoveStringLiteralDfa5_0(active0, 0x20000L); + return jjMoveStringLiteralDfa5_0(active0, 0x40000L); case 111: - return jjMoveStringLiteralDfa5_0(active0, 0x10000L); + return jjMoveStringLiteralDfa5_0(active0, 0x20000L); case 114: - return jjMoveStringLiteralDfa5_0(active0, 0xc0000L); + return jjMoveStringLiteralDfa5_0(active0, 0x180200L); case 115: - return jjMoveStringLiteralDfa5_0(active0, 0x8000L); + return jjMoveStringLiteralDfa5_0(active0, 0x10000L); default : break; } return jjStartNfa_0(3, active0); } -private int jjMoveStringLiteralDfa5_0(long old0, long active0) -{ +private int jjMoveStringLiteralDfa5_0(long old0, long active0){ if (((active0 &= old0)) == 0L) return jjStartNfa_0(3, old0); try { curChar = input_stream.readChar(); } @@ -376,32 +383,33 @@ private int jjMoveStringLiteralDfa5_0(long old0, long active0) switch(curChar) { case 97: - return jjMoveStringLiteralDfa6_0(active0, 0x4040000L); + return jjMoveStringLiteralDfa6_0(active0, 0x10080000L); case 100: - return jjMoveStringLiteralDfa6_0(active0, 0x20000L); + return jjMoveStringLiteralDfa6_0(active0, 0x40000L); case 103: - return jjMoveStringLiteralDfa6_0(active0, 0x500L); + return jjMoveStringLiteralDfa6_0(active0, 0x900L); case 105: - return jjMoveStringLiteralDfa6_0(active0, 0x8000L); + return jjMoveStringLiteralDfa6_0(active0, 0x10000L); case 110: - if ((active0 & 0x10000L) != 0L) - return jjStartNfaWithStates_0(5, 16, 30); + if ((active0 & 0x20000L) != 0L) + return jjStartNfaWithStates_0(5, 17, 35); break; case 116: - return jjMoveStringLiteralDfa6_0(active0, 0x4000L); + if ((active0 & 0x200L) != 0L) + return jjStartNfaWithStates_0(5, 9, 35); + return jjMoveStringLiteralDfa6_0(active0, 0x8000L); case 118: - return jjMoveStringLiteralDfa6_0(active0, 0x80000L); + return jjMoveStringLiteralDfa6_0(active0, 0x100000L); case 120: - if ((active0 & 0x200L) != 0L) - return jjStartNfaWithStates_0(5, 9, 30); + if ((active0 & 0x400L) != 0L) + return jjStartNfaWithStates_0(5, 10, 35); break; default : break; } return jjStartNfa_0(4, active0); } -private int jjMoveStringLiteralDfa6_0(long old0, long active0) -{ +private int jjMoveStringLiteralDfa6_0(long old0, long active0){ if (((active0 &= old0)) == 0L) return jjStartNfa_0(4, old0); try { curChar = input_stream.readChar(); } @@ -412,28 +420,27 @@ private int jjMoveStringLiteralDfa6_0(long old0, long active0) switch(curChar) { case 99: - return jjMoveStringLiteralDfa7_0(active0, 0x40000L); + return jjMoveStringLiteralDfa7_0(active0, 0x80000L); case 101: if ((active0 & 0x100L) != 0L) - return jjStartNfaWithStates_0(6, 8, 30); - else if ((active0 & 0x400L) != 0L) - return jjStartNfaWithStates_0(6, 10, 30); - return jjMoveStringLiteralDfa7_0(active0, 0x8c000L); + return jjStartNfaWithStates_0(6, 8, 35); + else if ((active0 & 0x800L) != 0L) + return jjStartNfaWithStates_0(6, 11, 35); + return jjMoveStringLiteralDfa7_0(active0, 0x118000L); case 110: - if ((active0 & 0x4000000L) != 0L) - return jjStartNfaWithStates_0(6, 26, 30); + if ((active0 & 0x10000000L) != 0L) + return jjStartNfaWithStates_0(6, 28, 35); break; case 115: - if ((active0 & 0x20000L) != 0L) - return jjStartNfaWithStates_0(6, 17, 30); + if ((active0 & 0x40000L) != 0L) + return jjStartNfaWithStates_0(6, 18, 35); break; default : break; } return jjStartNfa_0(5, active0); } -private int jjMoveStringLiteralDfa7_0(long old0, long active0) -{ +private int jjMoveStringLiteralDfa7_0(long old0, long active0){ if (((active0 &= old0)) == 0L) return jjStartNfa_0(5, old0); try { curChar = input_stream.readChar(); } @@ -444,24 +451,23 @@ private int jjMoveStringLiteralDfa7_0(long old0, long active0) switch(curChar) { case 100: - if ((active0 & 0x4000L) != 0L) - return jjStartNfaWithStates_0(7, 14, 30); - else if ((active0 & 0x80000L) != 0L) - return jjStartNfaWithStates_0(7, 19, 30); + if ((active0 & 0x8000L) != 0L) + return jjStartNfaWithStates_0(7, 15, 35); + else if ((active0 & 0x100000L) != 0L) + return jjStartNfaWithStates_0(7, 20, 35); break; case 110: - return jjMoveStringLiteralDfa8_0(active0, 0x8000L); + return jjMoveStringLiteralDfa8_0(active0, 0x10000L); case 116: - if ((active0 & 0x40000L) != 0L) - return jjStartNfaWithStates_0(7, 18, 30); + if ((active0 & 0x80000L) != 0L) + return jjStartNfaWithStates_0(7, 19, 35); break; default : break; } return jjStartNfa_0(6, active0); } -private int jjMoveStringLiteralDfa8_0(long old0, long active0) -{ +private int jjMoveStringLiteralDfa8_0(long old0, long active0){ if (((active0 &= old0)) == 0L) return jjStartNfa_0(6, old0); try { curChar = input_stream.readChar(); } @@ -472,8 +478,8 @@ private int jjMoveStringLiteralDfa8_0(long old0, long active0) switch(curChar) { case 116: - if ((active0 & 0x8000L) != 0L) - return jjStartNfaWithStates_0(8, 15, 30); + if ((active0 & 0x10000L) != 0L) + return jjStartNfaWithStates_0(8, 16, 35); break; default : break; @@ -497,7 +503,7 @@ private int jjStartNfaWithStates_0(int pos, int kind, int state) private int jjMoveNfa_0(int startState, int curPos) { int startsAt = 0; - jjnewStateCnt = 119; + jjnewStateCnt = 124; int i = 1; jjstateSet[0] = startState; int kind = 0x7fffffff; @@ -512,266 +518,288 @@ private int jjMoveNfa_0(int startState, int curPos) { switch(jjstateSet[--i]) { + case 55: case 35: - case 30: - if ((0x3ff000000000000L & l) == 0L) - break; - if (kind > 32) - kind = 32; - jjCheckNAdd(30); - break; - case 91: if ((0x3ff000000000000L & l) == 0L) break; - if (kind > 32) - kind = 32; - jjCheckNAdd(30); - break; - case 93: - if ((0x3ff000000000000L & l) == 0L) - break; - if (kind > 32) - kind = 32; - jjCheckNAdd(30); + if (kind > 36) + kind = 36; + { jjCheckNAdd(35); } break; - case 68: + case 96: if ((0x3ff000000000000L & l) == 0L) break; - if (kind > 32) - kind = 32; - jjCheckNAdd(30); + if (kind > 36) + kind = 36; + { jjCheckNAdd(35); } break; case 5: if ((0x3fe000000000000L & l) != 0L) { - if (kind > 28) - kind = 28; - jjCheckNAddTwoStates(11, 8); + if (kind > 32) + kind = 32; + { jjCheckNAddStates(0, 2); } } else if (curChar == 47) - jjAddStates(0, 4); + { jjAddStates(3, 7); } else if (curChar == 34) - jjCheckNAddStates(5, 7); + { jjCheckNAddStates(8, 10); } else if (curChar == 39) - jjCheckNAddStates(8, 10); + { jjCheckNAddStates(11, 13); } else if (curChar == 48) { - if (kind > 28) - kind = 28; - jjCheckNAdd(8); + if (kind > 32) + kind = 32; + { jjCheckNAddTwoStates(8, 10); } } else if (curChar == 45) - jjAddStates(11, 12); + { jjAddStates(14, 15); } break; - case 92: - if ((0x3ff000000000000L & l) == 0L) - break; - if (kind > 32) - kind = 32; - jjCheckNAdd(30); - break; - case 49: + case 54: if ((0x3ff000000000000L & l) != 0L) { - if (kind > 32) - kind = 32; - jjCheckNAdd(30); + if (kind > 36) + kind = 36; + { jjCheckNAdd(35); } } if (curChar == 54) - jjCheckNAdd(42); + { jjCheckNAdd(47); } else if (curChar == 51) - jjCheckNAdd(36); + { jjCheckNAdd(41); } break; - case 51: + case 40: if ((0x3ff000000000000L & l) == 0L) break; - if (kind > 32) - kind = 32; - jjCheckNAdd(30); + if (kind > 36) + kind = 36; + { jjCheckNAdd(35); } break; - case 50: + case 97: if ((0x3ff000000000000L & l) == 0L) break; - if (kind > 32) - kind = 32; - jjCheckNAdd(30); + if (kind > 36) + kind = 36; + { jjCheckNAdd(35); } + break; + case 73: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 36) + kind = 36; + { jjCheckNAdd(35); } + break; + case 98: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 36) + kind = 36; + { jjCheckNAdd(35); } + break; + case 56: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 36) + kind = 36; + { jjCheckNAdd(35); } break; case 6: if (curChar == 45) - jjAddStates(11, 12); + { jjAddStates(14, 15); } break; case 7: if (curChar != 48) break; - if (kind > 28) - kind = 28; - jjCheckNAdd(8); + if (kind > 32) + kind = 32; + { jjCheckNAddTwoStates(8, 10); } break; case 8: if (curChar == 46) - jjCheckNAdd(9); + { jjCheckNAdd(9); } break; case 9: if ((0x3ff000000000000L & l) == 0L) break; - if (kind > 28) - kind = 28; - jjCheckNAdd(9); + if (kind > 32) + kind = 32; + { jjCheckNAddTwoStates(9, 10); } break; - case 10: + case 11: + if ((0x280000000000L & l) != 0L) + { jjAddStates(16, 17); } + break; + case 12: + if (curChar == 48 && kind > 32) + kind = 32; + break; + case 13: if ((0x3fe000000000000L & l) == 0L) break; - if (kind > 28) - kind = 28; - jjCheckNAddTwoStates(11, 8); + if (kind > 32) + kind = 32; + { jjCheckNAdd(14); } break; - case 11: + case 14: if ((0x3ff000000000000L & l) == 0L) break; - if (kind > 28) - kind = 28; - jjCheckNAddTwoStates(11, 8); + if (kind > 32) + kind = 32; + { jjCheckNAdd(14); } + break; + case 15: + if ((0x3fe000000000000L & l) == 0L) + break; + if (kind > 32) + kind = 32; + { jjCheckNAddStates(0, 2); } + break; + case 16: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 32) + kind = 32; + { jjCheckNAddStates(0, 2); } break; - case 12: case 17: + case 22: if (curChar == 39) - jjCheckNAddStates(8, 10); + { jjCheckNAddStates(11, 13); } break; - case 13: + case 18: if ((0xffffff7fffffffffL & l) != 0L) - jjCheckNAddStates(8, 10); + { jjCheckNAddStates(11, 13); } break; - case 14: - if (curChar == 39 && kind > 29) - kind = 29; + case 19: + if (curChar == 39 && kind > 33) + kind = 33; break; - case 16: + case 21: if (curChar == 34) - jjCheckNAddStates(8, 10); + { jjCheckNAddStates(11, 13); } break; - case 19: - case 23: + case 24: + case 28: if (curChar == 34) - jjCheckNAddStates(5, 7); + { jjCheckNAddStates(8, 10); } break; - case 20: + case 25: if ((0xfffffffbffffffffL & l) != 0L) - jjCheckNAddStates(5, 7); + { jjCheckNAddStates(8, 10); } break; - case 21: - if (curChar == 34 && kind > 29) - kind = 29; + case 26: + if (curChar == 34 && kind > 33) + kind = 33; break; - case 24: + case 29: if (curChar == 39) - jjCheckNAddStates(5, 7); + { jjCheckNAddStates(8, 10); } break; - case 27: - jjAddStates(13, 14); + case 32: + { jjAddStates(18, 19); } break; - case 36: - if (curChar == 50 && kind > 27) - kind = 27; + case 41: + if (curChar == 50 && kind > 30) + kind = 30; break; - case 37: - case 56: - case 65: - case 69: + case 42: + case 61: + case 70: + case 74: if (curChar == 51) - jjCheckNAdd(36); + { jjCheckNAdd(41); } break; - case 42: - if (curChar == 52 && kind > 27) - kind = 27; + case 47: + if (curChar == 52 && kind > 30) + kind = 30; break; - case 43: - case 60: - case 75: - case 79: + case 48: + case 65: + case 80: + case 84: if (curChar == 54) - jjCheckNAdd(42); + { jjCheckNAdd(47); } break; - case 52: + case 57: if (curChar == 54) - jjCheckNAdd(42); + { jjCheckNAdd(47); } break; - case 98: + case 103: if (curChar == 47) - jjAddStates(0, 4); + { jjAddStates(3, 7); } break; - case 99: + case 104: if (curChar == 42) - jjCheckNAdd(100); + { jjCheckNAdd(105); } break; - case 100: + case 105: if ((0xfffffbffffffffffL & l) != 0L) - jjCheckNAddStates(15, 17); + { jjCheckNAddStates(20, 22); } break; - case 101: + case 106: if (curChar == 42) - jjstateSet[jjnewStateCnt++] = 102; + jjstateSet[jjnewStateCnt++] = 107; break; - case 102: + case 107: if ((0xffff7fffffffffffL & l) != 0L) - jjCheckNAddStates(15, 17); + { jjCheckNAddStates(20, 22); } break; - case 103: + case 108: if (curChar == 47 && kind > 5) kind = 5; break; - case 104: - case 105: + case 109: + case 110: if (curChar == 42) - jjCheckNAdd(103); + { jjCheckNAdd(108); } break; - case 106: + case 111: if (curChar == 42) - jjstateSet[jjnewStateCnt++] = 105; + jjstateSet[jjnewStateCnt++] = 110; break; - case 107: + case 112: if (curChar == 47) - jjCheckNAddTwoStates(108, 109); + { jjCheckNAddTwoStates(113, 114); } break; - case 108: + case 113: if ((0xffffffffffffdbffL & l) != 0L) - jjCheckNAddTwoStates(108, 109); + { jjCheckNAddTwoStates(113, 114); } break; - case 109: + case 114: if ((0x2400L & l) != 0L && kind > 6) kind = 6; break; - case 110: + case 115: if (curChar == 42) - jjCheckNAddStates(18, 20); + { jjCheckNAddStates(23, 25); } break; - case 111: + case 116: if ((0xfffffbffffffffffL & l) != 0L) - jjCheckNAddStates(18, 20); + { jjCheckNAddStates(23, 25); } break; - case 112: + case 117: if (curChar == 42) - jjstateSet[jjnewStateCnt++] = 113; + jjstateSet[jjnewStateCnt++] = 118; break; - case 113: + case 118: if ((0xffff7fffffffffffL & l) != 0L) - jjCheckNAddStates(18, 20); + { jjCheckNAddStates(23, 25); } break; - case 114: + case 119: if (curChar == 47 && kind > 7) kind = 7; break; - case 115: - case 117: + case 120: + case 122: if (curChar == 42) - jjCheckNAdd(114); + { jjCheckNAdd(119); } break; - case 116: + case 121: if (curChar == 42) - jjstateSet[jjnewStateCnt++] = 110; + jjstateSet[jjnewStateCnt++] = 115; break; - case 118: + case 123: if (curChar == 42) - jjstateSet[jjnewStateCnt++] = 117; + jjstateSet[jjnewStateCnt++] = 122; break; default : break; } @@ -784,130 +812,130 @@ else if (curChar < 128) { switch(jjstateSet[--i]) { - case 35: + case 55: if ((0x7fffffe87fffffeL & l) != 0L) { - if (kind > 32) - kind = 32; - jjCheckNAdd(30); + if (kind > 36) + kind = 36; + { jjCheckNAdd(35); } } - if (curChar == 105) - jjstateSet[jjnewStateCnt++] = 46; - else if (curChar == 108) - jjstateSet[jjnewStateCnt++] = 34; - if (curChar == 105) - jjstateSet[jjnewStateCnt++] = 40; + if (curChar == 116) + jjstateSet[jjnewStateCnt++] = 57; + if (curChar == 116) + jjstateSet[jjnewStateCnt++] = 54; break; - case 91: + case 96: if ((0x7fffffe87fffffeL & l) != 0L) { - if (kind > 32) - kind = 32; - jjCheckNAdd(30); + if (kind > 36) + kind = 36; + { jjCheckNAdd(35); } } if (curChar == 108) { - if (kind > 27) - kind = 27; + if (kind > 30) + kind = 30; } break; - case 93: - if ((0x7fffffe87fffffeL & l) != 0L) - { - if (kind > 32) - kind = 32; - jjCheckNAdd(30); - } - if (curChar == 121) - jjstateSet[jjnewStateCnt++] = 96; - else if (curChar == 111) - jjstateSet[jjnewStateCnt++] = 92; - break; - case 68: - if ((0x7fffffe87fffffeL & l) != 0L) - { - if (kind > 32) - kind = 32; - jjCheckNAdd(30); - } - if (curChar == 116) - jjstateSet[jjnewStateCnt++] = 88; - else if (curChar == 102) - jjstateSet[jjnewStateCnt++] = 83; - else if (curChar == 105) - jjstateSet[jjnewStateCnt++] = 77; - if (curChar == 102) - jjstateSet[jjnewStateCnt++] = 73; - else if (curChar == 105) - jjstateSet[jjnewStateCnt++] = 67; - break; case 5: if ((0x7fffffe87fffffeL & l) != 0L) { - if (kind > 32) - kind = 32; - jjCheckNAdd(30); + if (kind > 36) + kind = 36; + { jjCheckNAdd(35); } } else if (curChar == 96) - jjCheckNAdd(27); + { jjCheckNAdd(32); } if (curChar == 98) - jjAddStates(21, 22); + { jjAddStates(26, 27); } else if (curChar == 115) - jjAddStates(23, 27); + { jjAddStates(28, 32); } else if (curChar == 117) - jjAddStates(28, 29); + { jjAddStates(33, 34); } else if (curChar == 105) - jjAddStates(30, 31); + { jjAddStates(35, 36); } else if (curChar == 102) - jjAddStates(32, 34); + { jjAddStates(37, 39); } else if (curChar == 100) jjstateSet[jjnewStateCnt++] = 4; break; - case 92: + case 54: + case 35: + if ((0x7fffffe87fffffeL & l) == 0L) + break; + if (kind > 36) + kind = 36; + { jjCheckNAdd(35); } + break; + case 40: if ((0x7fffffe87fffffeL & l) != 0L) { - if (kind > 32) - kind = 32; - jjCheckNAdd(30); + if (kind > 36) + kind = 36; + { jjCheckNAdd(35); } + } + if (curChar == 105) + jjstateSet[jjnewStateCnt++] = 51; + else if (curChar == 108) + jjstateSet[jjnewStateCnt++] = 39; + if (curChar == 105) + jjstateSet[jjnewStateCnt++] = 45; + break; + case 97: + if ((0x7fffffe87fffffeL & l) != 0L) + { + if (kind > 36) + kind = 36; + { jjCheckNAdd(35); } } if (curChar == 111) - jjstateSet[jjnewStateCnt++] = 91; + jjstateSet[jjnewStateCnt++] = 96; break; - case 49: - case 30: - if ((0x7fffffe87fffffeL & l) == 0L) - break; - if (kind > 32) - kind = 32; - jjCheckNAdd(30); + case 73: + if ((0x7fffffe87fffffeL & l) != 0L) + { + if (kind > 36) + kind = 36; + { jjCheckNAdd(35); } + } + if (curChar == 116) + jjstateSet[jjnewStateCnt++] = 93; + else if (curChar == 102) + jjstateSet[jjnewStateCnt++] = 88; + else if (curChar == 105) + jjstateSet[jjnewStateCnt++] = 82; + if (curChar == 102) + jjstateSet[jjnewStateCnt++] = 78; + else if (curChar == 105) + jjstateSet[jjnewStateCnt++] = 72; break; - case 51: + case 98: if ((0x7fffffe87fffffeL & l) != 0L) { - if (kind > 32) - kind = 32; - jjCheckNAdd(30); + if (kind > 36) + kind = 36; + { jjCheckNAdd(35); } } - if (curChar == 110) - jjstateSet[jjnewStateCnt++] = 53; - if (curChar == 110) - jjstateSet[jjnewStateCnt++] = 50; + if (curChar == 121) + jjstateSet[jjnewStateCnt++] = 101; + else if (curChar == 111) + jjstateSet[jjnewStateCnt++] = 97; break; - case 50: + case 56: if ((0x7fffffe87fffffeL & l) != 0L) { - if (kind > 32) - kind = 32; - jjCheckNAdd(30); + if (kind > 36) + kind = 36; + { jjCheckNAdd(35); } } - if (curChar == 116) - jjstateSet[jjnewStateCnt++] = 52; - if (curChar == 116) - jjstateSet[jjnewStateCnt++] = 49; + if (curChar == 110) + jjstateSet[jjnewStateCnt++] = 58; + if (curChar == 110) + jjstateSet[jjnewStateCnt++] = 55; break; case 0: - if (curChar == 101 && kind > 27) - kind = 27; + if (curChar == 101 && kind > 30) + kind = 30; break; case 1: if (curChar == 108) @@ -925,140 +953,128 @@ else if (curChar == 100) if (curChar == 111) jjstateSet[jjnewStateCnt++] = 3; break; - case 13: + case 10: + if ((0x2000000020L & l) != 0L) + { jjAddStates(40, 42); } + break; + case 18: if ((0xffffffffefffffffL & l) != 0L) - jjCheckNAddStates(8, 10); + { jjCheckNAddStates(11, 13); } break; - case 15: + case 20: if (curChar == 92) - jjAddStates(35, 37); + { jjAddStates(43, 45); } break; - case 18: + case 23: if (curChar == 92) - jjCheckNAddStates(8, 10); + { jjCheckNAddStates(11, 13); } break; - case 20: + case 25: if ((0xffffffffefffffffL & l) != 0L) - jjCheckNAddStates(5, 7); + { jjCheckNAddStates(8, 10); } break; - case 22: + case 27: if (curChar == 92) - jjAddStates(38, 40); + { jjAddStates(46, 48); } break; - case 25: + case 30: if (curChar == 92) - jjCheckNAddStates(5, 7); + { jjCheckNAddStates(8, 10); } break; - case 26: + case 31: if (curChar == 96) - jjCheckNAdd(27); + { jjCheckNAdd(32); } break; - case 27: + case 32: if ((0xfffffffeffffffffL & l) != 0L) - jjCheckNAddTwoStates(27, 28); + { jjCheckNAddTwoStates(32, 33); } break; - case 28: - if (curChar == 96 && kind > 30) - kind = 30; + case 33: + if (curChar == 96 && kind > 34) + kind = 34; break; - case 29: + case 34: if ((0x7fffffe87fffffeL & l) == 0L) break; - if (kind > 32) - kind = 32; - jjCheckNAdd(30); + if (kind > 36) + kind = 36; + { jjCheckNAdd(35); } break; - case 31: + case 36: if (curChar == 102) - jjAddStates(32, 34); + { jjAddStates(37, 39); } break; - case 32: - if (curChar == 116 && kind > 27) - kind = 27; + case 37: + if (curChar == 116 && kind > 30) + kind = 30; break; - case 33: + case 38: if (curChar == 97) - jjstateSet[jjnewStateCnt++] = 32; + jjstateSet[jjnewStateCnt++] = 37; break; - case 34: + case 39: if (curChar == 111) - jjstateSet[jjnewStateCnt++] = 33; + jjstateSet[jjnewStateCnt++] = 38; break; - case 38: + case 43: if (curChar == 100) - jjstateSet[jjnewStateCnt++] = 37; + jjstateSet[jjnewStateCnt++] = 42; break; - case 39: + case 44: if (curChar == 101) - jjstateSet[jjnewStateCnt++] = 38; + jjstateSet[jjnewStateCnt++] = 43; break; - case 40: + case 45: if (curChar == 120) - jjstateSet[jjnewStateCnt++] = 39; + jjstateSet[jjnewStateCnt++] = 44; break; - case 41: + case 46: if (curChar == 105) - jjstateSet[jjnewStateCnt++] = 40; + jjstateSet[jjnewStateCnt++] = 45; break; - case 44: + case 49: if (curChar == 100) - jjstateSet[jjnewStateCnt++] = 43; + jjstateSet[jjnewStateCnt++] = 48; break; - case 45: + case 50: if (curChar == 101) - jjstateSet[jjnewStateCnt++] = 44; + jjstateSet[jjnewStateCnt++] = 49; break; - case 46: + case 51: if (curChar == 120) - jjstateSet[jjnewStateCnt++] = 45; - break; - case 47: - if (curChar == 105) - jjstateSet[jjnewStateCnt++] = 46; + jjstateSet[jjnewStateCnt++] = 50; break; - case 48: + case 52: if (curChar == 105) - jjAddStates(30, 31); + jjstateSet[jjnewStateCnt++] = 51; break; case 53: - if (curChar == 116) - jjstateSet[jjnewStateCnt++] = 52; - break; - case 54: - if (curChar == 110) - jjstateSet[jjnewStateCnt++] = 53; - break; - case 55: - if (curChar == 117) - jjAddStates(28, 29); - break; - case 57: - if (curChar == 116) - jjstateSet[jjnewStateCnt++] = 56; + if (curChar == 105) + { jjAddStates(35, 36); } break; case 58: - if (curChar == 110) + if (curChar == 116) jjstateSet[jjnewStateCnt++] = 57; break; case 59: - if (curChar == 105) + if (curChar == 110) jjstateSet[jjnewStateCnt++] = 58; break; - case 61: - if (curChar == 116) - jjstateSet[jjnewStateCnt++] = 60; + case 60: + if (curChar == 117) + { jjAddStates(33, 34); } break; case 62: - if (curChar == 110) + if (curChar == 116) jjstateSet[jjnewStateCnt++] = 61; break; case 63: - if (curChar == 105) + if (curChar == 110) jjstateSet[jjnewStateCnt++] = 62; break; case 64: - if (curChar == 115) - jjAddStates(23, 27); + if (curChar == 105) + jjstateSet[jjnewStateCnt++] = 63; break; case 66: if (curChar == 116) @@ -1068,108 +1084,124 @@ else if (curChar == 100) if (curChar == 110) jjstateSet[jjnewStateCnt++] = 66; break; - case 70: - if (curChar == 100) - jjstateSet[jjnewStateCnt++] = 69; + case 68: + if (curChar == 105) + jjstateSet[jjnewStateCnt++] = 67; + break; + case 69: + if (curChar == 115) + { jjAddStates(28, 32); } break; case 71: - if (curChar == 101) + if (curChar == 116) jjstateSet[jjnewStateCnt++] = 70; break; case 72: - if (curChar == 120) + if (curChar == 110) jjstateSet[jjnewStateCnt++] = 71; break; - case 73: - if (curChar == 105) - jjstateSet[jjnewStateCnt++] = 72; - break; - case 74: - if (curChar == 102) - jjstateSet[jjnewStateCnt++] = 73; + case 75: + if (curChar == 100) + jjstateSet[jjnewStateCnt++] = 74; break; case 76: - if (curChar == 116) + if (curChar == 101) jjstateSet[jjnewStateCnt++] = 75; break; case 77: - if (curChar == 110) + if (curChar == 120) jjstateSet[jjnewStateCnt++] = 76; break; case 78: if (curChar == 105) jjstateSet[jjnewStateCnt++] = 77; break; - case 80: - if (curChar == 100) - jjstateSet[jjnewStateCnt++] = 79; + case 79: + if (curChar == 102) + jjstateSet[jjnewStateCnt++] = 78; break; case 81: - if (curChar == 101) + if (curChar == 116) jjstateSet[jjnewStateCnt++] = 80; break; case 82: - if (curChar == 120) + if (curChar == 110) jjstateSet[jjnewStateCnt++] = 81; break; case 83: if (curChar == 105) jjstateSet[jjnewStateCnt++] = 82; break; - case 84: - if (curChar == 102) - jjstateSet[jjnewStateCnt++] = 83; - break; case 85: - if (curChar == 103 && kind > 27) - kind = 27; + if (curChar == 100) + jjstateSet[jjnewStateCnt++] = 84; break; case 86: - if (curChar == 110) + if (curChar == 101) jjstateSet[jjnewStateCnt++] = 85; break; case 87: - if (curChar == 105) + if (curChar == 120) jjstateSet[jjnewStateCnt++] = 86; break; case 88: - if (curChar == 114) + if (curChar == 105) jjstateSet[jjnewStateCnt++] = 87; break; case 89: - if (curChar == 116) + if (curChar == 102) jjstateSet[jjnewStateCnt++] = 88; break; case 90: - if (curChar == 98) - jjAddStates(21, 22); + if (curChar == 103 && kind > 30) + kind = 30; + break; + case 91: + if (curChar == 110) + jjstateSet[jjnewStateCnt++] = 90; + break; + case 92: + if (curChar == 105) + jjstateSet[jjnewStateCnt++] = 91; + break; + case 93: + if (curChar == 114) + jjstateSet[jjnewStateCnt++] = 92; break; case 94: - if (curChar == 115 && kind > 27) - kind = 27; + if (curChar == 116) + jjstateSet[jjnewStateCnt++] = 93; break; case 95: + if (curChar == 98) + { jjAddStates(26, 27); } + break; + case 99: + if (curChar == 115 && kind > 30) + kind = 30; + break; + case 100: if (curChar == 101) - jjstateSet[jjnewStateCnt++] = 94; + jjstateSet[jjnewStateCnt++] = 99; break; - case 96: + case 101: if (curChar == 116) - jjstateSet[jjnewStateCnt++] = 95; + jjstateSet[jjnewStateCnt++] = 100; break; - case 97: - if (curChar == 121) - jjstateSet[jjnewStateCnt++] = 96; - break; - case 100: case 102: - jjCheckNAddStates(15, 17); + if (curChar == 121) + jjstateSet[jjnewStateCnt++] = 101; break; - case 108: - jjAddStates(41, 42); + case 105: + case 107: + { jjCheckNAddStates(20, 22); } break; - case 111: case 113: - jjCheckNAddStates(18, 20); + { jjAddStates(49, 50); } + break; + case 116: + case 118: + { jjCheckNAddStates(23, 25); } break; default : break; } @@ -1177,7 +1209,7 @@ else if (curChar == 100) } else { - int hiByte = (int)(curChar >> 8); + int hiByte = (curChar >> 8); int i1 = hiByte >> 6; long l1 = 1L << (hiByte & 077); int i2 = (curChar & 0xff) >> 6; @@ -1186,33 +1218,33 @@ else if (curChar == 100) { switch(jjstateSet[--i]) { - case 13: + case 18: if (jjCanMove_0(hiByte, i1, i2, l1, l2)) - jjAddStates(8, 10); + { jjAddStates(11, 13); } break; - case 20: + case 25: if (jjCanMove_0(hiByte, i1, i2, l1, l2)) - jjAddStates(5, 7); + { jjAddStates(8, 10); } break; - case 27: + case 32: if (jjCanMove_0(hiByte, i1, i2, l1, l2)) - jjAddStates(13, 14); + { jjAddStates(18, 19); } break; - case 100: - case 102: + case 105: + case 107: if (jjCanMove_0(hiByte, i1, i2, l1, l2)) - jjCheckNAddStates(15, 17); + { jjCheckNAddStates(20, 22); } break; - case 108: + case 113: if (jjCanMove_0(hiByte, i1, i2, l1, l2)) - jjAddStates(41, 42); + { jjAddStates(49, 50); } break; - case 111: - case 113: + case 116: + case 118: if (jjCanMove_0(hiByte, i1, i2, l1, l2)) - jjCheckNAddStates(18, 20); + { jjCheckNAddStates(23, 25); } break; - default : break; + default : if (i1 == 0 || l1 == 0 || i2 == 0 || l2 == 0) break; else break; } } while(i != startsAt); } @@ -1223,103 +1255,24 @@ else if (curChar == 100) kind = 0x7fffffff; } ++curPos; - if ((i = jjnewStateCnt) == (startsAt = 119 - (jjnewStateCnt = startsAt))) + if ((i = jjnewStateCnt) == (startsAt = 124 - (jjnewStateCnt = startsAt))) return curPos; try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { return curPos; } } } -static final int[] jjnextStates = { - 99, 106, 107, 116, 118, 20, 21, 22, 13, 14, 15, 7, 10, 27, 28, 100, - 101, 104, 111, 112, 115, 93, 97, 68, 74, 78, 84, 89, 59, 63, 51, 54, - 35, 41, 47, 16, 17, 18, 23, 24, 25, 108, 109, -}; -private static final boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2) -{ - switch(hiByte) - { - case 0: - return ((jjbitVec2[i2] & l2) != 0L); - default : - if ((jjbitVec0[i1] & l1) != 0L) - return true; - return false; - } -} /** Token literal values. */ public static final String[] jjstrLiteralImages = { "", null, null, null, null, null, null, null, "\160\141\143\153\141\147\145", -"\163\171\156\164\141\170", "\155\145\163\163\141\147\145", "\145\156\165\155", "\155\141\160", -"\157\156\145\157\146", "\162\145\160\145\141\164\145\144", "\164\162\141\156\163\151\145\156\164", -"\157\160\164\151\157\156", "\145\170\164\145\156\144\163", "\141\142\163\164\162\141\143\164", -"\162\145\163\145\162\166\145\144", "\164\157", "\155\141\170", "\164\162\165\145", "\146\141\154\163\145", -"\151\156\164", "\154\157\156\147", "\142\157\157\154\145\141\156", null, null, null, null, -null, null, "\75", "\73", "\173", "\175", "\100", "\50", "\51", "\133", "\54", +"\151\155\160\157\162\164", "\163\171\156\164\141\170", "\155\145\163\163\141\147\145", +"\145\156\165\155", "\155\141\160", "\157\156\145\157\146", "\162\145\160\145\141\164\145\144", +"\164\162\141\156\163\151\145\156\164", "\157\160\164\151\157\156", "\145\170\164\145\156\144\163", +"\141\142\163\164\162\141\143\164", "\162\145\163\145\162\166\145\144", "\164\157", "\155\141\170", +"\164\162\165\145", "\146\141\154\163\145", "\156\165\154\154", "\151\156\164", +"\154\157\156\147", "\142\157\157\154\145\141\156", "\152\163\157\156", null, null, null, null, +null, null, null, "\75", "\73", "\173", "\175", "\100", "\50", "\51", "\133", "\54", "\135", "\74", "\76", "\56", }; - -/** Lexer state names. */ -public static final String[] lexStateNames = { - "DEFAULT", -}; -static final long[] jjtoToken = { - 0x3fff7fffff01L, -}; -static final long[] jjtoSkip = { - 0xfeL, -}; -static final long[] jjtoSpecial = { - 0x80L, -}; -protected SimpleCharStream input_stream; -private final int[] jjrounds = new int[119]; -private final int[] jjstateSet = new int[238]; -protected char curChar; -/** Constructor. */ -public ProtobufParserTokenManager(SimpleCharStream stream){ - if (SimpleCharStream.staticFlag) - throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer."); - input_stream = stream; -} - -/** Constructor. */ -public ProtobufParserTokenManager(SimpleCharStream stream, int lexState){ - this(stream); - SwitchTo(lexState); -} - -/** Reinitialise parser. */ -public void ReInit(SimpleCharStream stream) -{ - jjmatchedPos = jjnewStateCnt = 0; - curLexState = defaultLexState; - input_stream = stream; - ReInitRounds(); -} -private void ReInitRounds() -{ - int i; - jjround = 0x80000001; - for (i = 119; i-- > 0;) - jjrounds[i] = 0x80000000; -} - -/** Reinitialise parser. */ -public void ReInit(SimpleCharStream stream, int lexState) -{ - ReInit(stream); - SwitchTo(lexState); -} - -/** Switch to specified lex state. */ -public void SwitchTo(int lexState) -{ - if (lexState >= 1 || lexState < 0) - throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE); - else - curLexState = lexState; -} - protected Token jjFillToken() { final Token t; @@ -1343,6 +1296,24 @@ protected Token jjFillToken() return t; } +static final int[] jjnextStates = { + 16, 8, 10, 104, 111, 112, 121, 123, 25, 26, 27, 18, 19, 20, 7, 15, + 12, 13, 32, 33, 105, 106, 109, 116, 117, 120, 98, 102, 73, 79, 83, 89, + 94, 64, 68, 56, 59, 40, 46, 52, 11, 12, 13, 21, 22, 23, 28, 29, + 30, 113, 114, +}; +private static final boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2) +{ + switch(hiByte) + { + case 0: + return ((jjbitVec2[i2] & l2) != 0L); + default : + if ((jjbitVec0[i1] & l1) != 0L) + return true; + return false; + } +} int curLexState = 0; int defaultLexState = 0; @@ -1365,9 +1336,10 @@ public Token getNextToken() { curChar = input_stream.BeginToken(); } - catch(java.io.IOException e) + catch(Exception e) { jjmatchedKind = 0; + jjmatchedPos = -1; matchedToken = jjFillToken(); matchedToken.specialToken = specialToken; return matchedToken; @@ -1430,6 +1402,31 @@ public Token getNextToken() } } +void SkipLexicalActions(Token matchedToken) +{ + switch(jjmatchedKind) + { + default : + break; + } +} +void MoreLexicalActions() +{ + jjimageLen += (lengthOfMatch = jjmatchedPos + 1); + switch(jjmatchedKind) + { + default : + break; + } +} +void TokenLexicalActions(Token matchedToken) +{ + switch(jjmatchedKind) + { + default : + break; + } +} private void jjCheckNAdd(int state) { if (jjrounds[state] != jjround) @@ -1457,4 +1454,90 @@ private void jjCheckNAddStates(int start, int end) } while (start++ != end); } + /** Constructor. */ + public ProtobufParserTokenManager(SimpleCharStream stream){ + + if (SimpleCharStream.staticFlag) + throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer."); + + input_stream = stream; + } + + /** Constructor. */ + public ProtobufParserTokenManager (SimpleCharStream stream, int lexState){ + ReInit(stream); + SwitchTo(lexState); + } + + /** Reinitialise parser. */ + + public void ReInit(SimpleCharStream stream) + { + + + jjmatchedPos = + jjnewStateCnt = + 0; + curLexState = defaultLexState; + input_stream = stream; + ReInitRounds(); + } + + private void ReInitRounds() + { + int i; + jjround = 0x80000001; + for (i = 124; i-- > 0;) + jjrounds[i] = 0x80000000; + } + + /** Reinitialise parser. */ + public void ReInit(SimpleCharStream stream, int lexState) + + { + ReInit(stream); + SwitchTo(lexState); + } + + /** Switch to specified lex state. */ + public void SwitchTo(int lexState) + { + if (lexState >= 1 || lexState < 0) + throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE); + else + curLexState = lexState; + } + + +/** Lexer state names. */ +public static final String[] lexStateNames = { + "DEFAULT", +}; + +/** Lex State array. */ +public static final int[] jjnewLexState = { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +}; +static final long[] jjtoToken = { + 0x3fff77fffff01L, +}; +static final long[] jjtoSkip = { + 0xfeL, +}; +static final long[] jjtoSpecial = { + 0x80L, +}; +static final long[] jjtoMore = { + 0x0L, +}; + protected SimpleCharStream input_stream; + + private final int[] jjrounds = new int[124]; + private final int[] jjstateSet = new int[2 * 124]; + private final StringBuilder jjimage = new StringBuilder(); + private StringBuilder image = jjimage; + private int jjimageLen; + private int lengthOfMatch; + protected int curChar; } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/SimpleCharStream.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/SimpleCharStream.java index de86c161..9a90db51 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/SimpleCharStream.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/SimpleCharStream.java @@ -1,4 +1,4 @@ -/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 5.0 */ +/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 7.0 */ /* JavaCCOptions:STATIC=false,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ package de.haumacher.msgbuf.generator.parser; @@ -30,10 +30,12 @@ public class SimpleCharStream protected char[] buffer; protected int maxNextCharInd = 0; protected int inBuf = 0; - protected int tabSize = 8; + protected int tabSize = 1; + protected boolean trackLineColumn = true; + + public void setTabSize(int i) { tabSize = i; } + public int getTabSize() { return tabSize; } - protected void setTabSize(int i) { tabSize = i; } - protected int getTabSize(int i) { return tabSize; } protected void ExpandBuff(boolean wrapAround) @@ -201,22 +203,20 @@ public char readChar() throws java.io.IOException return c; } - @Deprecated /** * @deprecated * @see #getEndColumn */ - + @Deprecated public int getColumn() { return bufcolumn[bufpos]; } - @Deprecated /** * @deprecated * @see #getEndLine */ - + @Deprecated public int getLine() { return bufline[bufpos]; } @@ -466,6 +466,7 @@ public void adjustBeginLineColumn(int newLine, int newCol) line = bufline[j]; column = bufcolumn[j]; } - + boolean getTrackLineColumn() { return trackLineColumn; } + void setTrackLineColumn(boolean tlc) { trackLineColumn = tlc; } } -/* JavaCC - OriginalChecksum=20450f951b12894781ddaca18154f2a5 (do not edit this line) */ +/* JavaCC - OriginalChecksum=7719aed5156bff06c279316f3c0d5269 (do not edit this line) */ diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/Token.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/Token.java index d193d213..c481891a 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/Token.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/Token.java @@ -1,5 +1,5 @@ -/* Generated By:JavaCC: Do not edit this line. Token.java Version 5.0 */ -/* JavaCCOptions:TOKEN_EXTENDS=,KEEP_LINE_COL=null,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ +/* Generated By:JavaCC: Do not edit this line. Token.java Version 7.0 */ +/* JavaCCOptions:TOKEN_EXTENDS=,KEEP_LINE_COLUMN=true,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ package de.haumacher.msgbuf.generator.parser; /** @@ -129,4 +129,4 @@ public static Token newToken(int ofKind) } } -/* JavaCC - OriginalChecksum=a208cb97112a96f0d530f078c091d153 (do not edit this line) */ +/* JavaCC - OriginalChecksum=476326b3f9cd0dbecc94d1d9dbfcfb45 (do not edit this line) */ diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/TokenMgrError.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/TokenMgrError.java index c6b76370..dc490e67 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/TokenMgrError.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/TokenMgrError.java @@ -1,8 +1,9 @@ -/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 5.0 */ +/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 7.0 */ /* JavaCCOptions: */ package de.haumacher.msgbuf.generator.parser; /** Token Manager Error. */ +@SuppressWarnings("all") public class TokenMgrError extends Error { @@ -20,22 +21,22 @@ public class TokenMgrError extends Error /** * Lexical error occurred. */ - static final int LEXICAL_ERROR = 0; + public static final int LEXICAL_ERROR = 0; /** * An attempt was made to create a second instance of a static token manager. */ - static final int STATIC_LEXER_ERROR = 1; + public static final int STATIC_LEXER_ERROR = 1; /** * Tried to change to an invalid lexical state. */ - static final int INVALID_LEXICAL_STATE = 2; + public static final int INVALID_LEXICAL_STATE = 2; /** * Detected (and bailed out of) an infinite loop in the token manager. */ - static final int LOOP_DETECTED = 3; + public static final int LOOP_DETECTED = 3; /** * Indicates the reason why the exception is thrown. It will have @@ -48,13 +49,11 @@ public class TokenMgrError extends Error * equivalents in the given string */ protected static final String addEscapes(String str) { - StringBuffer retval = new StringBuffer(); + StringBuilder retval = new StringBuilder(); char ch; for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { - case 0 : - continue; case '\b': retval.append("\\b"); continue; @@ -97,19 +96,20 @@ protected static final String addEscapes(String str) { * token manager to indicate a lexical error. * Parameters : * EOFSeen : indicates if EOF caused the lexical error - * curLexState : lexical state in which this error occurred + * lexState : lexical state in which this error occurred * errorLine : line number when the error occurred * errorColumn : column number when the error occurred * errorAfter : prefix that was seen before this error occurred * curchar : the offending character * Note: You can customize the lexical error message by modifying this method. */ - protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) { - return("Lexical error at line " + - errorLine + ", column " + - errorColumn + ". Encountered: " + - (EOFSeen ? " " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") + - "after : \"" + addEscapes(errorAfter) + "\""); + protected static String LexicalErr(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, int curChar) { + return("Lexical error at line " + // + errorLine + ", column " + // + errorColumn + ". Encountered: " + // + (EOFSeen ? "" : ("'" + addEscapes(String.valueOf((char) curChar)) + "' (" + curChar + "),")) + // + (errorAfter == null || errorAfter.length() == 0 ? "" : " after prefix \"" + addEscapes(errorAfter) + "\"")) + // + (lexState == 0 ? "" : " (in lexical state " + lexState + ")"); } /** @@ -141,8 +141,8 @@ public TokenMgrError(String message, int reason) { } /** Full Constructor. */ - public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) { - this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); + public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, int curChar, int reason) { + this(LexicalErr(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); } } -/* JavaCC - OriginalChecksum=11f535bc78366d999591ad5d062f5010 (do not edit this line) */ +/* JavaCC - OriginalChecksum=c1e49e61881f69efa163e0b0f265a231 (do not edit this line) */ diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/protobuf.jj b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/protobuf.jj index c8830f16..644d89b2 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/protobuf.jj +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/protobuf.jj @@ -12,7 +12,7 @@ options PARSER_BEGIN(ProtobufParser) package de.haumacher.msgbuf.generator.parser; -import de.haumacher.msgbuf.generator.Util; +import de.haumacher.msgbuf.generator.common.Util; import de.haumacher.msgbuf.generator.ast.*; /** @@ -45,6 +45,7 @@ SPECIAL_TOKEN: TOKEN : { < PACKAGE : "package" > +| < IMPORT : "import" > | < SYNTAX : "syntax" > | < MESSAGE : "message" > | < ENUM : "enum" > @@ -60,9 +61,11 @@ TOKEN : | < MAX : "max" > | < TRUE : "true" > | < FALSE : "false" > +| < NULL : "null" > | < INT_TYPE : "int" > | < LONG_TYPE : "long" > | < BOOLEAN_TYPE : "boolean" > +| < JSON_TYPE : "json" > | < TYPE : "double" | "float" | @@ -80,7 +83,8 @@ TOKEN : "string" | "bytes" > -| < NUMBER : ( "-" )? ("0" | ( [ "1"-"9" ] ([ "0"-"9" ])* )) ("." ([ "0"-"9" ])+)? > +| < #INT: ("0" | ( [ "1"-"9" ] ([ "0"-"9" ])* )) > +| < NUMBER : ( "-" )? < INT > ("." ([ "0"-"9" ])+)? (["e", "E"] ( [ "+", "-" ] )? < INT > )? > | < STRING : "'" (~[ "'", "\\" ] | < QUOTE > )* "'" | "\"" (~[ "\"", "\\" ] | < QUOTE > )* "\"" > | < XNAME : "`" (~[ "`" ] )+ "`" > | < #QUOTE : "\\\\" | "\\'" | "\\\"" > @@ -92,18 +96,36 @@ DefinitionFile file() : DefinitionFile result = DefinitionFile.create(); QName pkgName; Definition def; + Token t; } { - ( < SYNTAX > "=" < STRING > ";" + ( + t=< SYNTAX > "=" < STRING > ";" + { + result.setComment(Util.stripComment(t)); + } )? ( - < PACKAGE > pkgName = qName() ";" + t=< PACKAGE > + { + if (result.getComment().isEmpty()) { + result.setComment(Util.stripComment(t)); + } + } + pkgName = qName() ";" { result.setPackage(pkgName); } )? - + + ( + < IMPORT > { Token importPath; } + importPath = < STRING > + { result.addImport(de.haumacher.msgbuf.generator.common.Util.stringContent(importPath.image)); } + ";" + )* + ( optionStatement(result) )* @@ -303,7 +325,7 @@ Field field() : Field result = Field.create(); Type type; String name; - Token index; + Token def; Token comment; Option option; Token optionName; @@ -330,9 +352,9 @@ Field field() : result.setName(name); } ( - "=" index=< NUMBER > + "=" (def=< NUMBER > | def=< TRUE > | def=< FALSE > | def=< STRING > | def=< NULL > ) { - result.setIndex(Integer.parseInt(index.image)); + result.setDefaultValue(def.image); } )? partOptions(result) @@ -442,6 +464,8 @@ PrimitiveType primitiveType() : { result = PrimitiveType.create().setKind(PrimitiveType.Kind.INT_64); } | t=< BOOLEAN_TYPE > { result = PrimitiveType.create().setKind(PrimitiveType.Kind.BOOL); } + | t=< JSON_TYPE > + { result = PrimitiveType.create().setKind(PrimitiveType.Kind.JSON); } ) { return result; } } @@ -503,6 +527,8 @@ String name() : { result = t.image; } | t = < MAX > { result = t.image; } + | t = < JSON_TYPE > + { result = t.image; } | t = < XNAME > { result = t.image.substring(1, t.image.length() - 1); } ) 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 aacef230..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 @@ -13,9 +13,11 @@ import java.util.Set; import de.haumacher.msgbuf.generator.AbstractMessageGenerator; +import de.haumacher.msgbuf.generator.CodeConvention; import de.haumacher.msgbuf.generator.GeneratorPlugin; import de.haumacher.msgbuf.generator.ast.CustomType; import de.haumacher.msgbuf.generator.ast.Definition; +import de.haumacher.msgbuf.generator.ast.EnumDef; import de.haumacher.msgbuf.generator.ast.Field; import de.haumacher.msgbuf.generator.ast.MessageDef; import de.haumacher.msgbuf.generator.ast.Option; @@ -30,6 +32,66 @@ * {@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; + + @Override + 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)) { + return; + } + + if (!def.hasExtends()) { + generalizations.add("de.haumacher.msgbuf.xml.XmlSerializable"); + } + } @Override public FileGenerator messageInterfaceContents(Map options, MessageDef def) { @@ -40,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 {"); @@ -62,17 +139,139 @@ public FileGenerator messageImplContents(Map options, MessageDef @Override protected void generate() { nl(); - line("/** XML element name representing a {@link " + typeName(def) + "} type. */"); + line("/** XML element name representing a {@link " + qTypeName(def) + "} type. */"); 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) + "\";"); } + if (!def.isAbstract()) { + nl(); + line("@Override"); + line("public String getXmlTagName() {"); + { + line("return " + xmlTypeNameConstant(def) + ";"); + } + line("}"); + } + + if (!def.hasExtends()) { + nl(); + line("@Override"); + line("public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException {"); + { + line("writeAttributes(out);"); + line("writeElements(out);"); + } + 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("/** Serializes all fields that are written as XML attributes. */"); + if (def.hasExtends()) { + line("@Override"); + } + line("protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException {"); + { + if (def.hasExtends()) { + 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("}"); + } + } + } + } + line("}"); + + nl(); + line("/** Serializes all fields that are written as XML elements. */"); + if (def.hasExtends()) { + line("@Override"); + } + line("protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException {"); + { + if (def.hasExtends()) { + line("super.writeElements(out);"); + } + + boolean hasElementFields = false; + for (Field field : def.getFields()) { + if (!xmlSerialized(field)) { + continue; + } + Type type = field.getType(); + switch (type.kind()) { + case PRIMITIVE_TYPE: { + continue; + } + + case CUSTOM_TYPE: { + Definition typeDefinition = ((CustomType) type).getDefinition(); + if (typeDefinition instanceof EnumDef) { + continue; + } + + hasElementFields = true; + boolean nullable = Util.isNullable(field); + if (nullable) { + line("if (" + CodeConvention.hasName(field) + "()" + ") {"); + } + { + line("out.writeStartElement(" + xmlFieldNameConstant(field) + ");"); + if (field.isRepeated()) { + line("for (" + qTypeName(typeDefinition) + " element : " + getterName(field) + "()) {"); + { + line("element.writeTo(out);"); + } + line("}"); + } else { + if (((MessageDef) typeDefinition).isAbstract()) { + // Create element encoding the type. + line(CodeConvention.getterName(field) + "()" + ".writeTo(out);"); + } else { + // Embed into field element. + line(CodeConvention.getterName(field) + "()" + ".writeContent(out);"); + } + } + line("out.writeEndElement();"); + } + if (nullable) { + line("}"); + } + } + } + } + + if (!hasElementFields) { + line("// No element fields."); + } + } + line("}"); + + nl(); + line("/** Creates a new {@link " + qTypeName(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 " + implName(def) + " " + readXmlContent(def) + "(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException {"); { if (def.isAbstract()) { @@ -89,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;"); } @@ -147,7 +359,10 @@ protected void generate() { line("switch (name) {"); { for (Field field : def.getFields()) { - if (field.getType().kind() == Type.TypeKind.PRIMITIVE_TYPE) { + if (!xmlSerialized(field)) { + continue; + } + if (field.getType().kind() == Type.TypeKind.PRIMITIVE_TYPE || isEnum(field.getType())) { line("case " + xmlFieldNameConstant(field) + ": {"); { line(setterName(field) + "(" + fromString(field, "value") + ");"); @@ -185,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; @@ -194,17 +412,17 @@ protected void generate() { switch (type.kind()) { case PRIMITIVE_TYPE: { - line("case " + xmlFieldNameConstant(field) + ": {"); - { - line(setterName(field) + "(" + fromString(field, "in.getElementText()") + ");"); - line("break;"); - } - line("}"); + readPrimitiveXmlElement(field); break; } case CUSTOM_TYPE: { Definition typeDefinition = ((CustomType) type).getDefinition(); + if (typeDefinition instanceof EnumDef) { + readPrimitiveXmlElement(field); + break; + } + if (field.getOptions().get("Embedded") != null) { if (!(typeDefinition instanceof MessageDef)) { System.err.println("ERROR: Only other messages can be embedded from '" + field.getName() + "'."); @@ -311,21 +529,76 @@ protected void generate() { } } + private void readPrimitiveXmlElement(Field field) { + line("case " + xmlFieldNameConstant(field) + ": {"); + { + 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; } + private boolean noXmlNames(Map options) { + return options.get("NoXmlNames") != null; + } + String readerMethod(MessageDef def) { return "read" + CodeUtil.firstUpperCase(def.getName()); } String xmlTypeName(MessageDef def) { + return xmlTypeName(def, _noXmlNames); + } + + private static String xmlTypeName(MessageDef def, boolean noXmlNames) { Optional