Parser contract

This page is the internal contract between parsing and the later stages of asyncapi-generator-core. It is for maintainers.

The only public API of core is AsyncApiGenerator in the package dev.banking.asyncapi.generator.core, with GeneratorSettings, ConfiguredGeneration, ProtocProvider, and AsyncApiGenerationException in the same package. Frontends and library users see nothing else. Everything on this page is internal and may change without notice.

Loading

AsyncApiDocumentLoader (package loader) runs the front half of every generation. Each call creates its own AsyncApiContext, so repeated and concurrent calls share no state. It runs four steps in order:

  1. Read and parse. SourceReader reads the root file (see the reader contract) and AsyncApiParser maps it to an AsyncApiDocument.
  2. Load. ExternalReferenceLoader reads the documents and fragments the references point at.
  3. Link. ReferenceLinker sets Reference.model on every reference.
  4. Validate. Each loaded document and fragment is validated on its own, then the root document.

Read, parse, and load failures are thrown, and every one of them is reported before any validation finding. Validation errors are thrown. Validation warnings come back with the result. Warnings found in external documents are merged with the root warnings, deduplicated by rule and source location, and never logged by the parser.

AsyncApiDocumentLoadResult holds the document, the warnings, the rendered warnings (formatWarnings(), empty when there are none), and sourceFiles. sourceFiles is the set of canonical files the load read: the root document, every external document, and every external native Avro or Protobuf schema asset. Each appears once, even when several references or cycles reach it. AsyncApiGenerator.inputFiles returns it, and the build plugins use it to track inputs.

The loader does not bundle or generate. Bundling and generation take over from the load result.

Reader output

The parser consumes the DocumentNode tree the reader produced. The node types, syntax rules, and limits are in the reader contract. The parser requires the root to be an object. Any other root produces an unexpected-value-type diagnostic at the root location, which keeps format syntax errors apart from AsyncAPI structure errors.

AsyncAPI specification versions

Before parsing the domain structure, AsyncApiParser requires asyncapi to be a string in major.minor.patch form with an optional alphanumeric suffix. The declared value is preserved in AsyncApiDocument, while its major/minor line selects an AsyncApiParserProfile. Patch releases share the same profile.

The parser recognizes the published 3.0 and 3.1 specification lines, but only the 3.0 parser profile is implemented. So 3.0.x documents are supported, including suffixed values such as 3.0.0-rc1; 3.1.x produces a diagnostic explaining that the version is known but its parser profile has not been implemented. Other version lines are unsupported rather than being silently interpreted as 3.0.

Profiles are carried by parser nodes. Complete external AsyncAPI documents select their own profile, while raw external fragments inherit the profile of the reference that loads them. Version-dependent parsing must use this profile instead of comparing the raw asyncapi string.

Parser cursor API

ParserNode is a source-aware cursor over one DocumentNode. Structural navigation is available only after selecting an object or array view.

Owner Operation Contract
ParserNode expectObject() Requires an object and returns its object navigation view
ParserNode expectArray() Requires an array and returns its indexed navigation view
ParserNode expect<T>() Checks the complete requested Kotlin runtime type, including nested list and map values
ParserNode toPlainValue() Recursively removes source metadata and returns maps, lists, scalars, or null
ParserObjectNode required(name) Requires the named member to be present and returns its cursor
ParserObjectNode optional(name) Returns the member cursor or null when absent
ParserObjectNode members() Returns one cursor per member, keyed by member name, in document order
ParserObjectNode extensions() Returns the x- members as plain values, or null when there are none
ParserObjectNode expectOnlyMembers(...) Rejects members outside an object's supported set and allowed specification extensions
ParserArrayNode elements() Returns one cursor per element with indexed paths

expect<T>() performs type checking, not coercion. A string is not converted to a boolean or number, and a scalar is not wrapped in a collection. Map keys and nested collection elements are checked recursively, so expect<Map<String, List<Boolean>>>() cannot hide an invalid nested value behind an unchecked cast.

expect<Any?>() and toPlainValue() both allow any JSON-compatible value. expect<T>() should be preferred when the AsyncAPI field has a defined shape; toPlainValue() communicates that source metadata is intentionally discarded at a free-form boundary.

Fixed-field object policy

The AsyncAPI 3.0 parser profile owns the allowed-member set for each ordinary fixed-field object. Domain parsers select the relevant object type and do not repeat large field sets locally. An unknown non-extension member produces parser.unexpected-object-member at the member key. A specification extension is accepted when its name matches x- followed by letters, digits, dots, underscores, or hyphens.

This policy applies to ordinary AsyncAPI objects such as Info, Server, Channel, Message, Operation, Components, Security Scheme, and their traits and nested fixed-field objects. It does not reinterpret patterned maps, bindings, Schema Objects, or deliberately free-form values as fixed-field objects.

Unconditional required fields are parser-owned. In particular, an inline Operation Object requires both action and channel. Whether the referenced channel resolves to the correct semantic target remains validator-owned.

Absent and null values

Absence and explicit null are different parser states.

Input state Object view optional("field") Object view required("field") expect<String>() expect<String?>()
Member absent null Missing-required-member diagnostic Not applicable Not applicable
Member is null Cursor over DocumentNull Cursor over DocumentNull Unexpected-value-type diagnostic null
Member is a string Cursor over DocumentString Cursor over DocumentString String value String value

Callers must not use a nullable expectation merely to make malformed nulls disappear. Use it only when the corresponding domain contract permits explicit null. When presence itself is significant, retain the member cursor separately; SchemaParser does this for default through its defaultSet flag.

Channel.address is a specification-defined nullable exception: absence and explicit null both produce a null domain value, while a non-string, non-null value is a structural parser error. JSON Schema nullability is expressed with a type union such as type: [string, "null"]; a Schema Object type: null is not a nullable schema.

Parser diagnostics

Strict parser failures throw AsyncApiParseException.ParserDiagnosticFailure. Its diagnostic is structured data; the exception message is a human-readable rendering with a source snippet.

Every ParserDiagnostic exposes:

  • a stable category and string code;
  • the display path of the node the failure is about; and
  • SourceLocation, containing file, path, one-based line, and one-based column.

Each diagnostic adds the fields of its kind, such as the missing member, the expected and actual type of a value, or the reference that cannot be loaded.

The categories are:

Code Meaning
parser.missing-required-member An object does not contain a required member
parser.unexpected-object-member An object contains a member that its parser does not recognize
parser.unexpected-value-type A value or nested value has the wrong runtime type
parser.invalid-specification-version The asyncapi value does not have the required version form
parser.unsupported-specification-version The declared version has no implemented parser profile
parser.invalid-reference A reference is not a supported URI reference with JSON Pointer semantics
parser.reference-document-not-found The external document does not exist or is unreadable
parser.reference-target-not-found The JSON Pointer target does not exist in the loaded document
parser.load-resource-limit-exceeded One complete load exceeded a configured source/reference resource budget
parser.unknown-schema-format A Multi Format Schema declares a schemaFormat that is not known
parser.native-schema-asset-unreadable The file a native Avro or Protobuf schema references cannot be read

Diagnostic messages may include targeted hints for common quoted scalar mistakes. The category and structured fields, rather than rendered prose, are the stable surface for programmatic assertions.

Internal identity and display paths

Tracking identifies nodes with a NodeAddress: the SourceId of the document, unique within one load, and the node's NodePath. A rendered dot path is never parsed to recover identity. This distinguishes a component named A.properties.x from property x below component A, and distinguishes an object member named "0" from array index 0.

Simple names use plain dot notation. Ambiguous names use quoted bracket notation with JSON string escaping. For example:

contract.root.components.schemas.Order
contract.root.components.schemas["Order.properties.id"]
contract.root.values["0"]
contract.root.values[0]

SourceLocation.path and parser diagnostic paths are presentation values. NodeLocations and ModelTracking use the segment-aware address directly.

Reference behavior

A Reference Object must be an object containing a string $ref. A missing member produces a missing-required-member diagnostic where a Reference Object is required; an explicit null or a non-string value produces an unexpected-value-type diagnostic at $ref. For reference-versus-inline fields, a present $ref controls discrimination. Once it is a valid string, sibling members are ignored as required by AsyncAPI 3.0 and are not checked against the inline object's member policy. Every parsed reference carries the concrete ReferenceCategoryKey of its target and records how to parse that target; the category is not inferred from substrings in the reference path.

Internal references do not load a file. Local relative paths and file: URIs are resolved relative to the source document that owns the reference. HTTP and other remote schemes are unsupported. Canonical file paths distinguish same-named files in different directories. URI percent encoding is decoded for file paths, and JSON Pointer ~0 and ~1 escapes are supported when selecting targets. Numeric-looking object keys remain object members rather than being mistaken for array indexes.

External targets have two modes:

  • A target document with an asyncapi member is parsed and validated as a full AsyncAPI document.
  • A fragment-only document is parsed and validated using the reference category, such as schema, message, channel, operation, server, parameter, or binding.

An external fragment container does not need to be an AsyncAPI document or have an object root. JSON Pointer selection can traverse object or array containers, and a root scalar can be selected directly when the reference category permits that value, such as a boolean Schema Object. The selected target must satisfy the structure required by its reference category. Only the selected target is parsed; unrelated siblings in a heterogeneous raw file are not interpreted as members of the same category. A whole-file Message reference therefore selects one Message Object at the document root. A raw map containing multiple named messages is a container rather than one Message Object and must select an individual message with an explicit JSON Pointer; the parser does not bulk import or splice container members.

References discovered inside a selected raw fragment retain their concrete category and resolve same-file JSON Pointers on demand. Reference chains and cycles are deduplicated by file, pointer, category, and parser profile. A missing same-file target is reported at the nested reference in the raw fragment that owns it.

Loading follows references depth first, in the order the parser met them, and deduplicates documents and targets. It preserves each file's source locations and does not bundle or inline the model.

After loading, every reference is linked: Reference.model points at the model or reference it targets. A link that never reaches a model of the expected kind (unresolved, a cycle, or a target of another kind) is reported by the validator, which never changes the model.

One load applies the whole-load limits in the reader contract. A limit failure is parser.load-resource-limit-exceeded.

Schema Object behavior

SchemaParser is specialized because Schema Objects are recursive and permit shapes that ordinary AsyncAPI objects do not:

  • Boolean schemas are represented as SchemaInterface.BooleanSchema only when the YAML or JSON value is an actual boolean. Quoted "true" and "false" values are strings and fail structural parsing.
  • String $ref values produce schema references.
  • An absent type is valid. A present type is parsed as a JsonSchemaType: Single for a string, Multiple for an array of strings, and it is written back in the same form. An explicit null is retained through field registration. The validator reports explicit null with the stable JSONSCHEMA-TYPE finding; it is not treated as absence. Nullable schemas use a union such as type: [string, "null"].
  • Recursive keywords such as properties, items, allOf, anyOf, oneOf, not, conditional schemas, and schema-valued dependencies recurse through SchemaParser.
  • items as one schema is Schema.items. items as an array of schemas (tuple form) is Schema.tupleItems. SchemaParser fills one or the other. The model, the bundler, and JSON Schema output keep tuple items. Source generation rejects them: SourceSchemaCompatibilityValidator in generator/input reports tuple-form items for the Kotlin and Java output that is asked for, not the validator.
  • Property dependencies are lists of strings; schema dependencies are parsed as schemas.
  • default, const, examples, and enum values preserve JSON-compatible plain values. defaultSet distinguishes an absent default from an explicit null.
  • Known AsyncAPI Schema Object formats delegate back to ordinary schema parsing. Known native or other Multi Format Schema values are preserved as MultiFormatSchema; native Avro and Protobuf schemas may load supported external schema assets.
  • Unknown schemaFormat values fail with parser.unknown-schema-format.

Schema Objects are not subject to ordinary AsyncAPI fixed-member rejection. Unknown and unsupported keywords remain registered with their original values and locations so SchemaRules can issue dialect or capability findings. Referencing a fragment from an OpenAPI-like or otherwise heterogeneous file does not switch parser dialects: the selected fragment still follows AsyncAPI 3.0 Schema Object and JSON Schema Draft 7 behavior, while unrelated surrounding content is ignored.

The schema parser constructs model shape. SchemaRules is responsible for semantic keyword policy and combinations.

Extensions and free-form values

Extension members beginning with x- and specification fields explicitly defined as free-form cross the typed parser boundary as JSON-compatible plain values: Map<String, Any?>, List<Any?>, String, Number, Boolean, or null.

Specification extensions are kept on the objects the specification marks as extensible. ParserObjectNode.extensions() collects them into the model's extensions field, and bundled output writes them back.

Use toPlainValue() only at those boundaries. The returned value has no SourceLocation, so the containing model and its registered field locations remain the source of downstream diagnostics. Known structural fields must use expect<T>(), expectObject(), or expectArray() instead of being treated as free-form.